跳至主要内容

中间件示例:会话数据

以下示例将每个 `Post` 的 `language` 字段设置为上下文语言(例如,从会话状态获取)。

const prisma = new PrismaClient()

const contextLanguage = 'en-us' // Session state

prisma.$use(async (params, next) => {
if (params.model == 'Post' && params.action == 'create') {
params.args.data.language = contextLanguage
}

return next(params)
})

const create = await prisma.post.create({
data: {
title: 'My post in English',
},
})

该示例基于以下示例模式。

generator client {
provider = "prisma-client-js"
}

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

model Post {
authorId Int?
content String?
id Int @id @default(autoincrement())
published Boolean @default(false)
title String
user User? @relation(fields: [authorId], references: [id])
language String?

@@index([authorId], name: "authorId")
}

model User {
email String @unique
id Int @id @default(autoincrement())
name String?
posts Post[]
extendedProfile Json?
role Role @default(USER)
}

enum Role {
ADMIN
USER
MODERATOR
}