|
| 1 | +import type { ClientContract } from '@zenstackhq/orm'; |
| 2 | +import type { SchemaDef } from '@zenstackhq/orm/schema'; |
| 3 | +import { Elysia, type Context as ElysiaContext } from 'elysia'; |
| 4 | +import { log } from '../../api/utils'; |
| 5 | +import type { CommonAdapterOptions } from '../common'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Options for initializing an Elysia middleware. |
| 9 | + */ |
| 10 | +export interface ElysiaOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> { |
| 11 | + /** |
| 12 | + * Callback method for getting a ZenStackClient instance for the given request context. |
| 13 | + */ |
| 14 | + getClient: (context: ElysiaContext) => Promise<ClientContract<Schema>> | ClientContract<Schema>; |
| 15 | + |
| 16 | + /** |
| 17 | + * Optional base path to strip from the request path before passing to the API handler. |
| 18 | + */ |
| 19 | + basePath?: string; |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Creates an Elysia middleware handler for ZenStack. |
| 24 | + * This handler provides automatic CRUD APIs through Elysia's routing system. |
| 25 | + */ |
| 26 | +export function createElysiaHandler<Schema extends SchemaDef>(options: ElysiaOptions<Schema>) { |
| 27 | + return async (app: Elysia) => { |
| 28 | + app.all('/*', async (ctx: ElysiaContext) => { |
| 29 | + const { request, body, set } = ctx; |
| 30 | + const client = await options.getClient(ctx); |
| 31 | + if (!client) { |
| 32 | + set.status = 500; |
| 33 | + return { |
| 34 | + message: 'unable to get ZenStackClient from request context', |
| 35 | + }; |
| 36 | + } |
| 37 | + |
| 38 | + const url = new URL(request.url); |
| 39 | + const query = Object.fromEntries(url.searchParams); |
| 40 | + let path = url.pathname; |
| 41 | + |
| 42 | + if (options.basePath && path.startsWith(options.basePath)) { |
| 43 | + path = path.slice(options.basePath.length); |
| 44 | + if (!path.startsWith('/')) { |
| 45 | + path = '/' + path; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + if (!path || path === '/') { |
| 50 | + set.status = 400; |
| 51 | + return { |
| 52 | + message: 'missing path parameter', |
| 53 | + }; |
| 54 | + } |
| 55 | + |
| 56 | + try { |
| 57 | + const r = await options.apiHandler.handleRequest({ |
| 58 | + method: request.method, |
| 59 | + path, |
| 60 | + query, |
| 61 | + requestBody: body, |
| 62 | + client, |
| 63 | + }); |
| 64 | + |
| 65 | + set.status = r.status; |
| 66 | + return r.body; |
| 67 | + } catch (err) { |
| 68 | + set.status = 500; |
| 69 | + log(options.apiHandler.log, 'error', `An unhandled error occurred while processing the request: ${err}${err instanceof Error ? '\n' + err.stack : ''}`); |
| 70 | + return { |
| 71 | + message: 'An internal server error occurred', |
| 72 | + }; |
| 73 | + } |
| 74 | + }); |
| 75 | + |
| 76 | + return app; |
| 77 | + }; |
| 78 | +} |
0 commit comments