Skip to content

Commit f377441

Browse files
authored
fix: allow 'null' values for optional fields in custom types (#1864)
1 parent 285b258 commit f377441

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,11 @@ export function generateTypeDefType(sourceFile: SourceFile, decl: TypeDef) {
1717
field.comments.forEach((c) => writer.writeLine(` * ${unwrapTripleSlashComment(c)}`));
1818
writer.writeLine(` */`);
1919
}
20+
// optional fields are also nullable (to be consistent with Prisma)
2021
writer.writeLine(
21-
` ${field.name}${field.type.optional ? '?' : ''}: ${zmodelTypeToTsType(field.type)};`
22+
` ${field.name}${field.type.optional ? '?' : ''}: ${zmodelTypeToTsType(field.type)}${
23+
field.type.optional ? ' | null' : ''
24+
};`
2225
);
2326
});
2427
});
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { loadSchema } from '@zenstackhq/testtools';
2+
3+
describe('issue 1857', () => {
4+
it('regression', async () => {
5+
const { zodSchemas } = await loadSchema(
6+
`
7+
type JSONContent {
8+
type String
9+
text String?
10+
}
11+
12+
model Post {
13+
id String @id @default(uuid())
14+
content JSONContent @json
15+
@@allow('all', true)
16+
}
17+
`,
18+
{
19+
provider: 'postgresql',
20+
pushDb: false,
21+
compile: true,
22+
extraSourceFiles: [
23+
{
24+
name: 'main.ts',
25+
content: `
26+
import { PrismaClient } from '@prisma/client';
27+
import { enhance } from '.zenstack/enhance';
28+
29+
async function main() {
30+
const prisma = new PrismaClient();
31+
await prisma.post.create({
32+
data: {
33+
content: { type: 'foo', text: null }
34+
}
35+
});
36+
}
37+
`,
38+
},
39+
],
40+
}
41+
);
42+
43+
zodSchemas.models.JSONContentSchema.parse({ type: 'foo', text: null });
44+
});
45+
});

0 commit comments

Comments
 (0)