-
-
Notifications
You must be signed in to change notification settings - Fork 12
feat(server): migrate sveltekit adapter #343
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| export * from './handler'; | ||
| export { createElysiaHandler, type ElysiaOptions } from './handler'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| export { ZenStackMiddleware, type MiddlewareOptions } from './middleware'; | ||
| export { ZenStackMiddleware, type ExpressMiddlewareOptions } from './middleware'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| export * from './handler'; | ||
| export { createHonoHandler, type HonoOptions } from './handler'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| export * from './handler'; | ||
| export { createEventHandler, type NuxtHandlerOptions } from './handler'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
ymc9 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
ymc9 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const path = event.url.pathname.substring(options.prefix.length); | ||
ymc9 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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 }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { SvelteKitHandler, type SvelteKitHandlerOptions } from './handler'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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: '[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('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: '[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) { | ||
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.