|
| 1 | +--- |
| 2 | +title: Elysia |
| 3 | +description: Adapter for integrating with Elysia |
| 4 | +sidebar_position: 8 |
| 5 | +--- |
| 6 | + |
| 7 | +import ErrorHandling from './_error-handling.md'; |
| 8 | +import AdapterOptions from './_options.mdx'; |
| 9 | +import UsingAPI from './_using-api.mdx' |
| 10 | + |
| 11 | +# Elysia Adapter |
| 12 | + |
| 13 | +The `@zenstackhq/server/elysia` module provides a quick way to install a CRUD middleware onto an [Elysia](https://elysiajs.com/) app. Combined with ZenStack's power of enhancing Prisma with access policies, you can achieve a secure data backend without manually coding it. |
| 14 | + |
| 15 | +### Installation |
| 16 | + |
| 17 | +```bash |
| 18 | +bun install @zenstackhq/server |
| 19 | +``` |
| 20 | + |
| 21 | +### Mounting the API |
| 22 | + |
| 23 | +You can use the `createElysiaHandler` API to create an Elysia request handler that handles CRUD requests automatically: |
| 24 | + |
| 25 | +```ts |
| 26 | +import { PrismaClient } from '@prisma/client'; |
| 27 | +import { Elysia, Context } from 'elysia'; |
| 28 | +import { enhance } from '@zenstackhq/runtime'; |
| 29 | +import { createElysiaHandler } from '@zenstackhq/server/elysia'; |
| 30 | + |
| 31 | +const prisma = new PrismaClient(); |
| 32 | + |
| 33 | +const app = new Elysia({ prefix: '/api' }); |
| 34 | + |
| 35 | +// install the CRUD middleware under route "/api/crud" |
| 36 | +app.group('/crud', (app) => |
| 37 | + app.use( |
| 38 | + createElysiaHandler({ |
| 39 | + getPrisma: (context) => enhance(prisma, { user: getCurrentUser(context) }), |
| 40 | + basePath: '/api/crud', |
| 41 | + }) |
| 42 | + ) |
| 43 | +); |
| 44 | + |
| 45 | +function getCurrentUser(context: Context) { |
| 46 | + // the implementation depends on your authentication mechanism |
| 47 | + ... |
| 48 | +} |
| 49 | + |
| 50 | +app.listen(3000); |
| 51 | +``` |
| 52 | + |
| 53 | +The middleware factory takes the following options to initialize: |
| 54 | + |
| 55 | +<AdapterOptions getPrisma='(ctx: Context) => unknown | Promise<unknown>' /> |
| 56 | + |
| 57 | +- basePath (optional) |
| 58 | + |
| 59 | + <blockquote>string</blockquote> |
| 60 | + |
| 61 | + Optional base path to strip from the request path before passing to the API handler. E.g., if your CRUD handler is mounted at `/api/crud`, set this field to `'/api/crud'`. |
| 62 | + |
| 63 | +### Using the API |
| 64 | + |
| 65 | +<UsingAPI /> |
| 66 | + |
| 67 | +<ErrorHandling /> |
0 commit comments