-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
101 lines (89 loc) · 2.55 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { PrismaClient, Prisma, User } from "@prisma/client";
// Validation library
const Joi = require("joi");
const joiSchema = Joi.object({
// We set a range for the age integer and we validate email adress.
age: Joi.number().integer().min(0).max(120).required(),
email: Joi.string().email().required(),
});
// Prisma client
const prisma = new PrismaClient();
// Extended Prisma Client which only adds `person` if the age and email are valid
const prismaWithCustomValidation = prisma.$extends({
// Customizing models works at runtime
model: {
user: {
// Create a custom method `validate` on user models. Returns true if data is valid.
validate(data: unknown): data is User {
const result = joiSchema.validate(data);
return !result.error;
},
},
},
});
async function main() {
console.log("Client Extensions Demo");
// Invalid user signup
await signup({ age: 150, email: "[email protected]" });
// Invalid user signup
await signup({ age: 50, email: "foobar.com" });
// Valid user signup
await signup({ age: 50, email: "[email protected]" });
}
async function signup(data: unknown) {
const userData = data;
if (prismaWithCustomValidation.user.validate(userData)) {
console.log("Valid!");
const user = await prismaWithCustomValidation.user.create({
data: userData,
});
} else {
// not valid
console.log("not valid, hence no user created");
}
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
const prismaWithCustomResultAndQuery = prisma.$extends({
// Customizing results only works on a type level for you to try, doesn't work at runtime yet!
result: {
user: {
needs: {
fullName: { firstName: true, lastName: true },
},
fields: {
fullName(user) {
return `${user.firstName} ${user.lastName}`;
},
},
},
},
// Customizing queries only works on a type level for you to try, doesn't work at runtime yet!
query: {
user: {
async create({ args, data }) {
const result = joiSchema.validate(data);
if (result.error) {
throw result.error;
}
return data;
},
},
},
});
// This breaks at runtime and is hence commented out. But it shows the auto complete for the virtual field on `user`
// const frederik = await prismaWithCustomResultAndQuery.user.findUnique({
// where: {
// id: 1,
// },
// });
// if (frederik) {
// console.log(frederik.fullName);
// }