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
15 changes: 15 additions & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,16 @@
"types": "./dist/nuxt.d.cts",
"default": "./dist/nuxt.cjs"
}
},
"./sveltekit": {
"import": {
"types": "./dist/sveltekit.d.ts",
"default": "./dist/sveltekit.js"
},
"require": {
"types": "./dist/sveltekit.d.cts",
"default": "./dist/sveltekit.cjs"
}
}
},
"dependencies": {
Expand All @@ -111,6 +121,7 @@
"zod-validation-error": "catalog:"
},
"devDependencies": {
"@sveltejs/kit": "^2.48.3",
"@types/body-parser": "^1.19.6",
"@types/express": "^5.0.0",
"@types/supertest": "^6.0.3",
Expand All @@ -131,6 +142,7 @@
"zod": "~3.25.0"
},
"peerDependencies": {
"@sveltejs/kit": "^2.0.0",
"elysia": "^1.3.0",
"express": "^5.0.0",
"fastify": "^5.0.0",
Expand Down Expand Up @@ -161,6 +173,9 @@
},
"nuxt": {
"optional": true
},
"@sveltejs/kit": {
"optional": true
}
}
}
2 changes: 1 addition & 1 deletion packages/server/src/adapter/elysia/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './handler';
export { createElysiaHandler, type ElysiaOptions } from './handler';
2 changes: 1 addition & 1 deletion packages/server/src/adapter/express/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { ZenStackMiddleware, type MiddlewareOptions } from './middleware';
export { ZenStackMiddleware, type ExpressMiddlewareOptions } from './middleware';
4 changes: 2 additions & 2 deletions packages/server/src/adapter/express/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { logInternalError, type CommonAdapterOptions } from '../common';
/**
* Express middleware options
*/
export interface MiddlewareOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
export interface ExpressMiddlewareOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
/**
* Callback for getting a ZenStackClient for the given request
*/
Expand All @@ -27,7 +27,7 @@ export interface MiddlewareOptions<Schema extends SchemaDef> extends CommonAdapt
/**
* Creates an Express middleware for handling CRUD requests.
*/
const factory = <Schema extends SchemaDef>(options: MiddlewareOptions<Schema>): Handler => {
const factory = <Schema extends SchemaDef>(options: ExpressMiddlewareOptions<Schema>): Handler => {
const requestHandler = options.apiHandler;

return async (request, response, next) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/adapter/fastify/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { ZenStackFastifyPlugin, type PluginOptions } from './plugin';
export { ZenStackFastifyPlugin, type FastifyPluginOptions } from './plugin';

4 changes: 2 additions & 2 deletions packages/server/src/adapter/fastify/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { logInternalError, type CommonAdapterOptions } from '../common';
/**
* Fastify plugin options
*/
export interface PluginOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
export interface FastifyPluginOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {

/**
* Url prefix, e.g.: /api
Expand All @@ -23,7 +23,7 @@ export interface PluginOptions<Schema extends SchemaDef> extends CommonAdapterOp
/**
* Fastify plugin for handling CRUD requests.
*/
const pluginHandler: FastifyPluginCallback<PluginOptions<SchemaDef>> = (fastify, options, done) => {
const pluginHandler: FastifyPluginCallback<FastifyPluginOptions<SchemaDef>> = (fastify, options, done) => {
const prefix = options.prefix ?? '';

fastify.all(`${prefix}/*`, async (request, reply) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/adapter/hono/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './handler';
export { createHonoHandler, type HonoOptions } from './handler';
4 changes: 2 additions & 2 deletions packages/server/src/adapter/nuxt/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ import { logInternalError, type CommonAdapterOptions } from '../common';
/**
* Nuxt request handler options
*/
export interface HandlerOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
export interface NuxtHandlerOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
/**
* Callback for getting a ZenStackClient for the given request
*/
getClient: (event: H3Event<EventHandlerRequest>) => ClientContract<Schema> | Promise<ClientContract<Schema>>;
}

export function createEventHandler<Schema extends SchemaDef>(options: HandlerOptions<Schema>) {
export function createEventHandler<Schema extends SchemaDef>(options: NuxtHandlerOptions<Schema>) {
return defineEventHandler(async (event) => {
const client = await options.getClient(event);
if (!client) {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/adapter/nuxt/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './handler';
export { createEventHandler, type NuxtHandlerOptions } from './handler';
78 changes: 78 additions & 0 deletions packages/server/src/adapter/sveltekit/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import type { Handle, RequestEvent } from '@sveltejs/kit';
import type { ClientContract } from '@zenstackhq/orm';
import type { SchemaDef } from '@zenstackhq/orm/schema';
import { logInternalError, type CommonAdapterOptions } from '../common';

/**
* SvelteKit request handler options
*/
export interface SvelteKitHandlerOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {
/**
* Url prefix, e.g.: /api
*/
prefix: string;

/**
* Callback for getting a ZenStackClient for the given request
*/
getClient: (event: RequestEvent) => ClientContract<Schema> | Promise<ClientContract<Schema>>;
}

/**
* SvelteKit server hooks handler for handling CRUD requests.
*/
export default function createHandler<Schema extends SchemaDef>(options: SvelteKitHandlerOptions<Schema>): Handle {
return async ({ event, resolve }) => {
if (event.url.pathname.startsWith(options.prefix)) {
const client = await options.getClient(event);
if (!client) {
return new Response(JSON.stringify({ message: 'unable to get ZenStackClient from request context' }), {
status: 400,
headers: {
'content-type': 'application/json',
},
});
}

const query = Object.fromEntries(event.url.searchParams);
let requestBody: unknown;
if (event.request.body) {
const text = await event.request.text();
if (text) {
requestBody = JSON.parse(text);
}
}

const path = event.url.pathname.substring(options.prefix.length);

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

return new Response(JSON.stringify(r.body), {
status: r.status,
headers: {
'content-type': 'application/json',
},
});
} catch (err) {
logInternalError(options.apiHandler.log, err);
return new Response(JSON.stringify({ message: 'An internal server error occurred' }), {
status: 500,
headers: {
'content-type': 'application/json',
},
});
}
}

return resolve(event);
};
}

export { createHandler as SvelteKitHandler };
1 change: 1 addition & 0 deletions packages/server/src/adapter/sveltekit/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { SvelteKitHandler, type SvelteKitHandlerOptions } from './handler';
154 changes: 154 additions & 0 deletions packages/server/test/adapter/sveltekit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { createTestClient } from '@zenstackhq/testtools';
import superjson from 'superjson';
import { describe, expect, it } from 'vitest';
import { SvelteKitHandler } from '../../src/adapter/sveltekit';
import { RestApiHandler, RPCApiHandler } from '../../src/api';
import { makeUrl, schema } from '../utils';

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

const handler = SvelteKitHandler({ prefix: '/api', getClient: () => client, 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: 'user1@abc.com',
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: 'user1@abc.com',
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: 'user1@def.com' } })
);
expect(r.status).toBe(200);
expect((await unmarshal(r)).data.email).toBe('user1@def.com');

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('SvelteKit adapter tests - rest handler', () => {
it('properly handles requests', async () => {
const client = await createTestClient(schema);

const handler = SvelteKitHandler({
prefix: '/api',
getClient: () => client,
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: 'user1@abc.com' },
},
})
);
expect(r.status).toBe(201);
expect(await unmarshal(r)).toMatchObject({
data: {
id: 'user1',
attributes: {
email: 'user1@abc.com',
},
},
});

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: 'user1@def.com' } },
})
);
expect(r.status).toBe(200);
expect((await unmarshal(r)).data.attributes.email).toBe('user1@def.com');

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) {
const payload = body ? JSON.stringify(body) : undefined;
return {
event: {
request: new Request(`http://localhost${path}`, { method, body: payload }),
url: new URL(`http://localhost${path}`),
} as any,
resolve: async () => {
throw new Error('should not be called');
},
};
}

async function unmarshal(r: Response, useSuperJson = false) {
const text = await r.text();
return (useSuperJson ? superjson.parse(text) : JSON.parse(text)) as any;
}
1 change: 1 addition & 0 deletions packages/server/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export default defineConfig({
elysia: 'src/adapter/elysia/index.ts',
nuxt: 'src/adapter/nuxt/index.ts',
hono: 'src/adapter/hono/index.ts',
sveltekit: 'src/adapter/sveltekit/index.ts',
},
outDir: 'dist',
splitting: false,
Expand Down
Loading
Loading