Middleware sample: session data
The following example sets the language
field of each Post
to the context language (taken, for example, from session state):
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',
},
})
The example is based on the following sample schema:
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
}