Skip to content

feat: add elysiajs #2114

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 4 commits into from
May 18, 2025
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
4 changes: 3 additions & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"express",
"nextjs",
"sveltekit",
"nuxtjs"
"nuxtjs",
"elysia"
],
"author": "ZenStack Team",
"license": "MIT",
Expand All @@ -48,6 +49,7 @@
"@types/supertest": "^2.0.12",
"@zenstackhq/testtools": "workspace:*",
"body-parser": "^1.20.2",
"elysia": "^1.3.1",
"express": "^4.19.2",
"fastify": "^4.14.1",
"fastify-plugin": "^4.5.0",
Expand Down
82 changes: 82 additions & 0 deletions packages/server/src/elysia/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { DbClientContract } from '@zenstackhq/runtime';
import { Elysia, Context as ElysiaContext } from 'elysia';
import { RPCApiHandler } from '../api';
import { loadAssets } from '../shared';
import { AdapterBaseOptions } from '../types';

/**
* Options for initializing an Elysia middleware.
*/
export interface ElysiaOptions extends AdapterBaseOptions {
/**
* Callback method for getting a Prisma instance for the given request context.
*/
getPrisma: (context: ElysiaContext) => Promise<unknown> | unknown;
/**
* 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(options: ElysiaOptions) {
const { modelMeta, zodSchemas } = loadAssets(options);
const requestHandler = options.handler ?? RPCApiHandler();

return async (app: Elysia) => {
app.all('/*', async (ctx: ElysiaContext) => {
const { request, body, set } = ctx;
const prisma = (await options.getPrisma(ctx)) as DbClientContract;
if (!prisma) {
set.status = 500;
return {
message: 'unable to get prisma 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 requestHandler({
method: request.method,
path,
query,
requestBody: body,
prisma,
modelMeta,
zodSchemas,
logger: options.logger,
});

set.status = r.status;
return r.body;
} catch (err) {
set.status = 500;
return {
message: 'An internal server error occurred',
};
}
});

return app;
};
}
1 change: 1 addition & 0 deletions packages/server/src/elysia/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './handler';
200 changes: 200 additions & 0 deletions packages/server/tests/adapter/elysia.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-explicit-any */
/// <reference types="@types/jest" />
import { loadSchema } from '@zenstackhq/testtools';
import 'isomorphic-fetch';
import path from 'path';
import superjson from 'superjson';
import Rest from '../../src/api/rest';
import { createElysiaHandler } from '../../src/elysia';
import { makeUrl, schema } from '../utils';
import { Elysia } from 'elysia';

describe('Elysia adapter tests - rpc handler', () => {
it('run hooks regular json', async () => {
const { prisma, zodSchemas } = await loadSchema(schema);

const handler = await createElysiaApp(
createElysiaHandler({ getPrisma: () => prisma, zodSchemas, basePath: '/api' })
);

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);
});

it('custom load path', async () => {
const { prisma, projectDir } = await loadSchema(schema, { output: './zen' });

const handler = await createElysiaApp(
createElysiaHandler({
getPrisma: () => prisma,
basePath: '/api',
modelMeta: require(path.join(projectDir, './zen/model-meta')).default,
zodSchemas: require(path.join(projectDir, './zen/zod')),
})
);

const 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);
});
});

describe('Elysia adapter tests - rest handler', () => {
it('run hooks', async () => {
const { prisma, modelMeta, zodSchemas } = await loadSchema(schema);

const handler = await createElysiaApp(
createElysiaHandler({
getPrisma: () => prisma,
basePath: '/api',
handler: Rest({ endpoint: 'http://localhost/api' }),
modelMeta,
zodSchemas,
})
);

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(makeUrl('/api/user/user1'))));
expect(r.status).toBe(200);
expect(await prisma.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
Loading