Skip to content

Commit 06ac296

Browse files
authored
Add logic to store service instance to global for dev environment as recommended by Prisma (#23)
1 parent b2fd336 commit 06ac296

File tree

3 files changed

+26
-18
lines changed

3 files changed

+26
-18
lines changed

packages/schema/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"publisher": "zenstack",
44
"displayName": "ZenStack Language Tools",
55
"description": "ZenStack is a toolkit that simplifies full-stack development",
6-
"version": "0.1.54",
6+
"version": "0.1.55",
77
"author": {
88
"name": "ZenStack Team"
99
},

packages/schema/src/generator/service/index.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ export default class ServiceGenerator implements Generator {
2727
isTypeOnly: true,
2828
});
2929

30+
sf.addVariableStatement({
31+
declarationKind: VariableDeclarationKind.Let,
32+
declarations: [
33+
{
34+
name: 'guardModule',
35+
type: 'any',
36+
},
37+
],
38+
});
39+
3040
const cls = sf.addClass({
3141
name: 'ZenStackService',
3242
isExported: true,
@@ -44,15 +54,6 @@ export default class ServiceGenerator implements Generator {
4454
.addBody()
4555
.setBodyText('return this._prisma;');
4656

47-
sf.addVariableStatement({
48-
declarationKind: VariableDeclarationKind.Let,
49-
declarations: [
50-
{
51-
name: 'guardModule',
52-
type: 'any',
53-
},
54-
],
55-
});
5657
cls
5758
.addMethod({
5859
name: 'resolveField',
@@ -100,7 +101,14 @@ export default class ServiceGenerator implements Generator {
100101
return provider(context);
101102
`);
102103

103-
sf.addStatements(['export default new ZenStackService();']);
104+
// Recommended by Prisma for Next.js
105+
// https://www.prisma.io/docs/guides/database/troubleshooting-orm/help-articles/nextjs-prisma-client-dev-practices#problem
106+
sf.addStatements([
107+
'declare global { var zenstackService: ZenStackService | undefined}',
108+
'const service = global.zenstackService || new ZenStackService();',
109+
'export default service;',
110+
`if (process.env.NODE_ENV !== 'production') global.zenstackService = service;`,
111+
]);
104112

105113
sf.formatText();
106114
await project.save();

samples/todo/package-lock.json

Lines changed: 7 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)