Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"next": "^15.0.0",
"fastify": "^5.6.1",
"fastify-plugin": "^5.1.0",
"elysia": "^1.3.1",
"supertest": "^7.1.4",
"zod": "~3.25.0"
},
Expand All @@ -81,6 +82,7 @@
"next": "^15.0.0",
"fastify": "^5.0.0",
"fastify-plugin": "^5.0.0",
"elysia": "^1.3.0",
"zod": "catalog:"
},
"peerDependenciesMeta": {
Expand All @@ -95,6 +97,9 @@
},
"fastify-plugin": {
"optional": true
},
"elysia": {
"optional": true
}
}
}
78 changes: 78 additions & 0 deletions packages/server/src/adapter/elysia/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import type { ClientContract } from '@zenstackhq/orm';
import type { SchemaDef } from '@zenstackhq/orm/schema';
import { Elysia, type Context as ElysiaContext } from 'elysia';
import { log } from '../../api/utils';
import type { CommonAdapterOptions } from '../common';

/**
* Options for initializing an Elysia middleware.
*/
export interface ElysiaOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
/**
* Callback method for getting a ZenStackClient instance for the given request context.
*/
getClient: (context: ElysiaContext) => Promise<ClientContract<Schema>> | ClientContract<Schema>;

/**
* Optional base path to strip from the request path before passing to the API handler.
*/
basePath?: string;
}

/**
* Creates an Elysia middleware handler for ZenStack.
* This handler provides automatic CRUD APIs through Elysia's routing system.
*/
export function createElysiaHandler<Schema extends SchemaDef>(options: ElysiaOptions<Schema>) {
return async (app: Elysia) => {
app.all('/*', async (ctx: ElysiaContext) => {
const { request, body, set } = ctx;
const client = await options.getClient(ctx);
if (!client) {
set.status = 500;
return {
message: 'unable to get ZenStackClient from request context',
};
}

const url = new URL(request.url);
const query = Object.fromEntries(url.searchParams);
let path = url.pathname;

if (options.basePath && path.startsWith(options.basePath)) {
path = path.slice(options.basePath.length);
if (!path.startsWith('/')) {
path = '/' + path;
}
}

if (!path || path === '/') {
set.status = 400;
return {
message: 'missing path parameter',
};
}

try {
const r = await options.apiHandler.handleRequest({
method: request.method,
path,
query,
requestBody: body,
client,
});

set.status = r.status;
return r.body;
} catch (err) {
set.status = 500;
log(options.apiHandler.log, 'error', `An unhandled error occurred while processing the request: ${err}${err instanceof Error ? '\n' + err.stack : ''}`);
return {
message: 'An internal server error occurred',
};
}
});

return app;
};
}
1 change: 1 addition & 0 deletions packages/server/src/adapter/elysia/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './handler';
4 changes: 3 additions & 1 deletion packages/server/src/adapter/express/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ClientContract } from '@zenstackhq/orm';
import type { SchemaDef } from '@zenstackhq/orm/schema';
import type { Handler, Request, Response } from 'express';
import { log } from '../../api/utils';
import type { CommonAdapterOptions } from '../common';

/**
Expand Down Expand Up @@ -70,7 +71,8 @@ const factory = <Schema extends SchemaDef>(options: MiddlewareOptions<Schema>):
if (sendResponse === false) {
throw err;
}
return response.status(500).json({ message: `An unhandled error occurred: ${err}` });
log(options.apiHandler.log, 'error', `An unhandled error occurred while processing the request: ${err}${err instanceof Error ? '\n' + err.stack : ''}`);
return response.status(500).json({ message: `An internal server error occurred` });
}
};
};
Expand Down
4 changes: 3 additions & 1 deletion packages/server/src/adapter/fastify/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ClientContract } from '@zenstackhq/orm';
import type { SchemaDef } from '@zenstackhq/orm/schema';
import type { FastifyPluginCallback, FastifyReply, FastifyRequest } from 'fastify';
import fp from 'fastify-plugin';
import { log } from '../../api/utils';
import type { CommonAdapterOptions } from '../common';

/**
Expand Down Expand Up @@ -43,7 +44,8 @@ const pluginHandler: FastifyPluginCallback<PluginOptions<SchemaDef>> = (fastify,
});
reply.status(response.status).send(response.body);
} catch (err) {
reply.status(500).send({ message: `An unhandled error occurred: ${err}` });
log(options.apiHandler.log, 'error', `An unhandled error occurred while processing the request: ${err}${err instanceof Error ? '\n' + err.stack : ''}`);
reply.status(500).send({ message: `An internal server error occurred` });
}

return reply;
Expand Down
4 changes: 3 additions & 1 deletion packages/server/src/adapter/next/app-route-handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { SchemaDef } from '@zenstackhq/orm/schema';
import { NextRequest, NextResponse } from 'next/server';
import type { AppRouteRequestHandlerOptions } from '.';
import { log } from '../../api/utils';

type Context = { params: Promise<{ path: string[] }> };

Expand Down Expand Up @@ -58,7 +59,8 @@ export default function factory<Schema extends SchemaDef>(
});
return NextResponse.json(r.body, { status: r.status });
} catch (err) {
return NextResponse.json({ message: `An unhandled error occurred: ${err}` }, { status: 500 });
log(options.apiHandler.log, 'error', `An unhandled error occurred while processing the request: ${err}${err instanceof Error ? '\n' + err.stack : ''}`);
return NextResponse.json({ message: 'An internal server error occurred' }, { status: 500 });
}
};
}
4 changes: 3 additions & 1 deletion packages/server/src/adapter/next/pages-route-handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { SchemaDef } from '@zenstackhq/orm/schema';
import type { NextApiRequest, NextApiResponse } from 'next';
import type { PageRouteRequestHandlerOptions } from '.';
import { log } from '../../api/utils';

/**
* Creates a Next.js API endpoint "pages" router request handler that handles ZenStack CRUD requests.
Expand Down Expand Up @@ -34,7 +35,8 @@ export default function factory<Schema extends SchemaDef>(
});
res.status(r.status).send(r.body);
} catch (err) {
res.status(500).send({ message: `An unhandled error occurred: ${err}` });
log(options.apiHandler.log, 'error', `An unhandled error occurred while processing the request: ${err}${err instanceof Error ? '\n' + err.stack : ''}`);
res.status(500).send({ message: 'An internal server error occurred' });
}
};
}
4 changes: 4 additions & 0 deletions packages/server/src/api/rest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,10 @@ export class RestApiHandler<Schema extends SchemaDef> implements ApiHandler<Sche
return this.options.schema;
}

get log(): LogConfig | undefined {
return this.options.log;
}

private buildUrlPatternMap(urlSegmentNameCharset: string): Record<UrlPatterns, UrlPattern> {
const options = { segmentValueCharset: urlSegmentNameCharset };

Expand Down
4 changes: 4 additions & 0 deletions packages/server/src/api/rpc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ export class RPCApiHandler<Schema extends SchemaDef> implements ApiHandler<Schem
return this.options.schema;
}

get log(): LogConfig | undefined {
return this.options.log;
}

async handleRequest({ client, method, path, query, requestBody }: RequestContext<Schema>): Promise<Response> {
const parts = path.split('/').filter((p) => !!p);
const op = parts.pop();
Expand Down
5 changes: 5 additions & 0 deletions packages/server/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ export interface ApiHandler<Schema extends SchemaDef> {
*/
get schema(): Schema;

/**
* Logging configuration.
*/
get log(): LogConfig | undefined;

/**
* Handle an API request.
*/
Expand Down
164 changes: 164 additions & 0 deletions packages/server/test/adapter/elysia.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import { createTestClient } from '@zenstackhq/testtools';
import { Elysia } from 'elysia';
import superjson from 'superjson';
import { describe, expect, it } from 'vitest';
import { createElysiaHandler } from '../../src/adapter/elysia';
import { RestApiHandler, RPCApiHandler } from '../../src/api';
import { makeUrl, schema } from '../utils';

describe('Elysia adapter tests - rpc handler', () => {
it('properly handles requests', async () => {
const client = await createTestClient(schema);

const handler = await createElysiaApp(
createElysiaHandler({ getClient: () => client, basePath: '/api', apiHandler: new RPCApiHandler({ schema: client.schema }) })
);

let r = await handler(makeRequest('GET', makeUrl('/api/post/findMany', { where: { id: { equals: '1' } } })));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toHaveLength(0);

r = await handler(
makeRequest('POST', '/api/user/create', {
include: { posts: true },
data: {
id: 'user1',
email: '[email protected]',
posts: {
create: [
{ title: 'post1', published: true, viewCount: 1 },
{ title: 'post2', published: false, viewCount: 2 },
],
},
},
})
);
expect(r.status).toBe(201);
expect((await unmarshal(r)).data).toMatchObject({
email: '[email protected]',
posts: expect.arrayContaining([
expect.objectContaining({ title: 'post1' }),
expect.objectContaining({ title: 'post2' }),
]),
});

r = await handler(makeRequest('GET', makeUrl('/api/post/findMany')));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toHaveLength(2);

r = await handler(makeRequest('GET', makeUrl('/api/post/findMany', { where: { viewCount: { gt: 1 } } })));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toHaveLength(1);

r = await handler(
makeRequest('PUT', '/api/user/update', { where: { id: 'user1' }, data: { email: '[email protected]' } })
);
expect(r.status).toBe(200);
expect((await unmarshal(r)).data.email).toBe('[email protected]');

r = await handler(makeRequest('GET', makeUrl('/api/post/count', { where: { viewCount: { gt: 1 } } })));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toBe(1);

r = await handler(makeRequest('GET', makeUrl('/api/post/aggregate', { _sum: { viewCount: true } })));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data._sum.viewCount).toBe(3);

r = await handler(
makeRequest('GET', makeUrl('/api/post/groupBy', { by: ['published'], _sum: { viewCount: true } }))
);
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toEqual(
expect.arrayContaining([
expect.objectContaining({ published: true, _sum: { viewCount: 1 } }),
expect.objectContaining({ published: false, _sum: { viewCount: 2 } }),
])
);

r = await handler(makeRequest('DELETE', makeUrl('/api/user/deleteMany', { where: { id: 'user1' } })));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data.count).toBe(1);
});
});

describe('Elysia adapter tests - rest handler', () => {
it('properly handles requests', async () => {
const client = await createTestClient(schema);

const handler = await createElysiaApp(
createElysiaHandler({
getClient: () => client,
basePath: '/api',
apiHandler: new RestApiHandler({schema: client.$schema, endpoint: 'http://localhost/api' }),
})
);

let r = await handler(makeRequest('GET', makeUrl('/api/post/1')));
expect(r.status).toBe(404);

r = await handler(
makeRequest('POST', '/api/user', {
data: {
type: 'user',
attributes: { id: 'user1', email: '[email protected]' },
},
})
);
expect(r.status).toBe(201);
expect(await unmarshal(r)).toMatchObject({
data: {
id: 'user1',
attributes: {
email: '[email protected]',
},
},
});

r = await handler(makeRequest('GET', makeUrl('/api/user?filter[id]=user1')));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toHaveLength(1);

r = await handler(makeRequest('GET', makeUrl('/api/user?filter[id]=user2')));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toHaveLength(0);

r = await handler(makeRequest('GET', makeUrl('/api/user?filter[id]=user1&filter[email]=xyz')));
expect(r.status).toBe(200);
expect((await unmarshal(r)).data).toHaveLength(0);

r = await handler(
makeRequest('PUT', makeUrl('/api/user/user1'), {
data: { type: 'user', attributes: { email: '[email protected]' } },
})
);
expect(r.status).toBe(200);
expect((await unmarshal(r)).data.attributes.email).toBe('[email protected]');

r = await handler(makeRequest('DELETE', makeUrl('/api/user/user1')));
expect(r.status).toBe(200);
expect(await client.user.findMany()).toHaveLength(0);
});
});

function makeRequest(method: string, path: string, body?: any) {
if (body) {
return new Request(`http://localhost${path}`, {
method,
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
} else {
return new Request(`http://localhost${path}`, { method });
}
}

async function unmarshal(r: Response, useSuperJson = false) {
const text = await r.text();
return (useSuperJson ? superjson.parse(text) : JSON.parse(text)) as any;
}

async function createElysiaApp(middleware: (app: Elysia) => Promise<Elysia>) {
const app = new Elysia();
await middleware(app);
return app.handle;
}
Loading