Skip to content

Commit 7f8050b

Browse files
feat: add elysiajs
1 parent 922e3c4 commit 7f8050b

File tree

4 files changed

+261
-0
lines changed

4 files changed

+261
-0
lines changed

packages/server/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"@types/supertest": "^2.0.12",
4949
"@zenstackhq/testtools": "workspace:*",
5050
"body-parser": "^1.20.2",
51+
"elysia": "^1.3.1",
5152
"express": "^4.19.2",
5253
"fastify": "^4.14.1",
5354
"fastify-plugin": "^4.5.0",
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { DbClientContract } from '@zenstackhq/runtime';
2+
import { Elysia, Context as ElysiaContext } from 'elysia';
3+
import { RPCApiHandler } from '../api';
4+
import { loadAssets } from '../shared';
5+
import { AdapterBaseOptions } from '../types';
6+
7+
/**
8+
* Options for initializing an Elysia middleware.
9+
*/
10+
export interface ElysiaOptions extends AdapterBaseOptions {
11+
/**
12+
* Callback method for getting a Prisma instance for the given request context.
13+
*/
14+
getPrisma: (context: ElysiaContext) => Promise<unknown> | unknown;
15+
}
16+
17+
/**
18+
* Creates an Elysia middleware handler for ZenStack.
19+
* This handler provides RPC API functionality through Elysia's routing system.
20+
*/
21+
export function createElysiaHandler(options: ElysiaOptions) {
22+
const { modelMeta, zodSchemas } = loadAssets(options);
23+
const requestHandler = options.handler ?? RPCApiHandler();
24+
25+
return async (app: Elysia) => {
26+
app.all('/*', async ({ request, body, set }: ElysiaContext) => {
27+
const prisma = (await options.getPrisma({ request, body, set } as ElysiaContext)) as DbClientContract;
28+
if (!prisma) {
29+
set.status = 500;
30+
return {
31+
message: 'unable to get prisma from request context'
32+
};
33+
}
34+
35+
const url = new URL(request.url);
36+
const query = Object.fromEntries(url.searchParams);
37+
const path = url.pathname;
38+
39+
if (!path) {
40+
set.status = 400;
41+
return {
42+
message: 'missing path parameter'
43+
};
44+
}
45+
46+
try {
47+
const r = await requestHandler({
48+
method: request.method,
49+
path,
50+
query,
51+
requestBody: body,
52+
prisma,
53+
modelMeta,
54+
zodSchemas,
55+
logger: options.logger,
56+
});
57+
58+
set.status = r.status;
59+
return r.body;
60+
} catch (err) {
61+
set.status = 500;
62+
return {
63+
message: `An unhandled error occurred: ${err}`
64+
};
65+
}
66+
});
67+
68+
return app;
69+
};
70+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './handler';
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
/* eslint-disable @typescript-eslint/no-var-requires */
2+
/* eslint-disable @typescript-eslint/no-explicit-any */
3+
/// <reference types="@types/jest" />
4+
import { loadSchema } from '@zenstackhq/testtools';
5+
import 'isomorphic-fetch';
6+
import path from 'path';
7+
import superjson from 'superjson';
8+
import Rest from '../../src/api/rest';
9+
import { createElysiaHandler } from '../../src/elysia';
10+
import { makeUrl, schema } from '../utils';
11+
import { Elysia } from 'elysia';
12+
13+
describe('Elysia adapter tests - rpc handler', () => {
14+
it('run hooks regular json', async () => {
15+
const { prisma, zodSchemas } = await loadSchema(schema);
16+
17+
const handler = await createElysiaApp(createElysiaHandler({ getPrisma: () => prisma, zodSchemas }));
18+
19+
let r = await handler(makeRequest('GET', makeUrl('/api/post/findMany', { where: { id: { equals: '1' } } })));
20+
expect(r.status).toBe(200);
21+
expect((await unmarshal(r)).data).toHaveLength(0);
22+
23+
r = await handler(
24+
makeRequest('POST', '/api/user/create', {
25+
include: { posts: true },
26+
data: {
27+
id: 'user1',
28+
29+
posts: {
30+
create: [
31+
{ title: 'post1', published: true, viewCount: 1 },
32+
{ title: 'post2', published: false, viewCount: 2 },
33+
],
34+
},
35+
},
36+
})
37+
);
38+
expect(r.status).toBe(201);
39+
expect((await unmarshal(r)).data).toMatchObject({
40+
41+
posts: expect.arrayContaining([
42+
expect.objectContaining({ title: 'post1' }),
43+
expect.objectContaining({ title: 'post2' }),
44+
]),
45+
});
46+
47+
r = await handler(makeRequest('GET', makeUrl('/api/post/findMany')));
48+
expect(r.status).toBe(200);
49+
expect((await unmarshal(r)).data).toHaveLength(2);
50+
51+
r = await handler(makeRequest('GET', makeUrl('/api/post/findMany', { where: { viewCount: { gt: 1 } } })));
52+
expect(r.status).toBe(200);
53+
expect((await unmarshal(r)).data).toHaveLength(1);
54+
55+
r = await handler(
56+
makeRequest('PUT', '/api/user/update', { where: { id: 'user1' }, data: { email: '[email protected]' } })
57+
);
58+
expect(r.status).toBe(200);
59+
expect((await unmarshal(r)).data.email).toBe('[email protected]');
60+
61+
r = await handler(makeRequest('GET', makeUrl('/api/post/count', { where: { viewCount: { gt: 1 } } })));
62+
expect(r.status).toBe(200);
63+
expect((await unmarshal(r)).data).toBe(1);
64+
65+
r = await handler(makeRequest('GET', makeUrl('/api/post/aggregate', { _sum: { viewCount: true } })));
66+
expect(r.status).toBe(200);
67+
expect((await unmarshal(r)).data._sum.viewCount).toBe(3);
68+
69+
r = await handler(
70+
makeRequest('GET', makeUrl('/api/post/groupBy', { by: ['published'], _sum: { viewCount: true } }))
71+
);
72+
expect(r.status).toBe(200);
73+
expect((await unmarshal(r)).data).toEqual(
74+
expect.arrayContaining([
75+
expect.objectContaining({ published: true, _sum: { viewCount: 1 } }),
76+
expect.objectContaining({ published: false, _sum: { viewCount: 2 } }),
77+
])
78+
);
79+
80+
r = await handler(makeRequest('DELETE', makeUrl('/api/user/deleteMany', { where: { id: 'user1' } })));
81+
expect(r.status).toBe(200);
82+
expect((await unmarshal(r)).data.count).toBe(1);
83+
});
84+
85+
it('custom load path', async () => {
86+
const { prisma, projectDir } = await loadSchema(schema, { output: './zen' });
87+
88+
const handler = await createElysiaApp(
89+
createElysiaHandler({
90+
getPrisma: () => prisma,
91+
modelMeta: require(path.join(projectDir, './zen/model-meta')).default,
92+
zodSchemas: require(path.join(projectDir, './zen/zod')),
93+
})
94+
);
95+
96+
const r = await handler(
97+
makeRequest('POST', '/api/user/create', {
98+
include: { posts: true },
99+
data: {
100+
id: 'user1',
101+
102+
posts: {
103+
create: [
104+
{ title: 'post1', published: true, viewCount: 1 },
105+
{ title: 'post2', published: false, viewCount: 2 },
106+
],
107+
},
108+
},
109+
})
110+
);
111+
expect(r.status).toBe(201);
112+
});
113+
});
114+
115+
describe('Elysia adapter tests - rest handler', () => {
116+
it('run hooks', async () => {
117+
const { prisma, modelMeta, zodSchemas } = await loadSchema(schema);
118+
119+
const handler = await createElysiaApp(
120+
createElysiaHandler({
121+
getPrisma: () => prisma,
122+
handler: Rest({ endpoint: 'http://localhost/api' }),
123+
modelMeta,
124+
zodSchemas,
125+
})
126+
);
127+
128+
let r = await handler(makeRequest('GET', makeUrl('/api/post/1')));
129+
expect(r.status).toBe(404);
130+
131+
r = await handler(
132+
makeRequest('POST', '/api/user', {
133+
data: {
134+
type: 'user',
135+
attributes: { id: 'user1', email: '[email protected]' },
136+
},
137+
})
138+
);
139+
expect(r.status).toBe(201);
140+
expect(await unmarshal(r)).toMatchObject({
141+
data: {
142+
id: 'user1',
143+
attributes: {
144+
145+
},
146+
},
147+
});
148+
149+
r = await handler(makeRequest('GET', makeUrl('/api/user?filter[id]=user1')));
150+
expect(r.status).toBe(200);
151+
expect((await unmarshal(r)).data).toHaveLength(1);
152+
153+
r = await handler(makeRequest('GET', makeUrl('/api/user?filter[id]=user2')));
154+
expect(r.status).toBe(200);
155+
expect((await unmarshal(r)).data).toHaveLength(0);
156+
157+
r = await handler(makeRequest('GET', makeUrl('/api/user?filter[id]=user1&filter[email]=xyz')));
158+
expect(r.status).toBe(200);
159+
expect((await unmarshal(r)).data).toHaveLength(0);
160+
161+
r = await handler(
162+
makeRequest('PUT', makeUrl('/api/user/user1'), {
163+
data: { type: 'user', attributes: { email: '[email protected]' } },
164+
})
165+
);
166+
expect(r.status).toBe(200);
167+
expect((await unmarshal(r)).data.attributes.email).toBe('[email protected]');
168+
169+
r = await handler(makeRequest('DELETE', makeUrl(makeUrl('/api/user/user1'))));
170+
expect(r.status).toBe(200);
171+
expect(await prisma.user.findMany()).toHaveLength(0);
172+
});
173+
});
174+
175+
function makeRequest(method: string, path: string, body?: any) {
176+
const payload = body ? JSON.stringify(body) : undefined;
177+
return new Request(`http://localhost${path}`, { method, body: payload });
178+
}
179+
180+
async function unmarshal(r: Response, useSuperJson = false) {
181+
const text = await r.text();
182+
return (useSuperJson ? superjson.parse(text) : JSON.parse(text)) as any;
183+
}
184+
185+
async function createElysiaApp(middleware: (app: Elysia) => Promise<Elysia>) {
186+
const app = new Elysia();
187+
await middleware(app);
188+
return app.handle;
189+
}

0 commit comments

Comments
 (0)