Skip to content
我们的赞助商

Prisma

Prisma 是一个 ORM,允许我们以类型安全的方式与数据库交互。

它提供了一种使用 Prisma schema 文件定义数据库模式的方法,然后基于该模式生成 TypeScript 类型。

Prismabox

Prismabox 是一个可以从 Prisma 模式生成 TypeBox 或 Elysia 验证模型的库。

我们可以使用 Prismabox 将 Prisma 模式转换为 Elysia 验证模型,然后用于确保 Elysia 中的类型验证。

工作原理:

  1. 在 Prisma Schema 中定义数据库模式。
  2. 添加 prismabox 生成器以生成 Elysia 模式。
  3. 使用转换后的 Elysia 验证模型确保类型验证。
  4. 从 Elysia 验证模型生成 OpenAPI 模式。
  5. 添加 Eden Treaty 为前端添加类型安全。
                                                    * ——————————————— *
                                                    |                 |
                                               | -> |     文档生成     |
* ————————— *             * ———————— * OpenAPI |    |                 |
|           |  prismabox  |          | ——————— |    * ——————————————— *
|  Prisma   | —————————-> |  Elysia  |
|           |             |          | ——————— |    * ——————————————— *
* ————————— *             * ———————— *   Eden  |    |                 |
                                               | -> |    前端代码     |
												    |                 |
												    * ——————————————— *

安装

要安装 Prisma,请运行以下命令:

bash
bun add @prisma/client prismabox && \
bun add -d prisma

Prisma 模式

假设您已经有一个 prisma/schema.prisma 文件。

我们可以将 prismabox 生成器添加到 Prisma 模式文件中,如下所示:

ts
generator client {
  provider = "prisma-client-js"
  output   = "../generated/prisma"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

generator prismabox { 
  provider = "prismabox"
  typeboxImportDependencyName = "elysia"
  typeboxImportVariableName = "t"
  inputModel = true
  output   = "../generated/prismabox"
} 

model User {
  id    String  @id @default(cuid())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id    	String  @id @default(cuid())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  String
}

这将在 generated/prismabox 目录中生成 Elysia 验证模型。

每个模型将有自己的文件,模型名称将基于 Prisma 模型名称。

例如:

  • User 模型将生成到 generated/prismabox/User.ts
  • Post 模型将生成到 generated/prismabox/Post.ts

使用生成的模型

然后我们可以在 Elysia 应用程序中导入生成的模型:

ts
import { Elysia, t } from 'elysia'

import { PrismaClient } from '../generated/prisma'
import { UserPlain, UserPlainInputCreate } from '../generated/prismabox/User'

const prisma = new PrismaClient()

const app = new Elysia()
    .put(
        '/',
        async ({ body }) =>
            prisma.user.create({
                data: body
            }),
        {
            body: UserPlainInputCreate, 
            response: UserPlain 
        }
    )
    .get(
        '/id/:id',
        async ({ params: { id }, status }) => {
            const user = await prisma.user.findUnique({
                where: { id }
            })

            if (!user) return status(404, 'User not found')

            return user
        },
        {
            response: {
                200: UserPlain, 
                404: t.String() 
            }
        }
    )
    .listen(3000)

console.log(
    `🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
)

这使我们能够在 Elysia 验证模型中重用数据库模式。


更多信息,请参考 PrismaPrismabox 文档。