Session data middleware

The following example sets the language property of each Post to the context language (taken, for example, from session state):

script.ts
1const prisma = new PrismaClient();
2
3const contextLanguage = "en-us"; // Session state
4
5prisma.$use(async (params, next) => {
6 if (params.model == "Post" && params.action == "create") {
7 params.args.data.language = contextLanguage;
8 }
9
10 return next(params);
11});
12
13const create = await prisma.post.create({
14 data: {
15 title: "My post in English",
16 },
17});

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 @default(autoincrement()) @id
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 @default(autoincrement()) @id
name String?
posts Post[]
extendedProfile Json?
role Role @default(USER)
}
enum Role {
ADMIN
USER
MODERATOR
}
Edit this page on GitHub