Skip to content

fix(zod): add coercion call when generating schema for DateTime field #1068

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/schema/src/plugins/zod/utils/schema-gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ function makeZodSchema(field: DataModelField) {
schema = 'z.boolean()';
break;
case 'DateTime':
schema = 'z.date()';
schema = 'z.coerce.date()';
break;
case 'Bytes':
schema = 'z.union([z.string(), z.instanceof(Uint8Array)])';
Expand Down
90 changes: 89 additions & 1 deletion packages/server/tests/api/rest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,11 @@ describe('REST server tests', () => {
id Int @id @default(autoincrement())
createdAt DateTime @default (now())
updatedAt DateTime @updatedAt
title String
title String @length(1, 10)
author User? @relation(fields: [authorId], references: [myId])
authorId String?
published Boolean @default(false)
publishedAt DateTime?
viewCount Int @default(0)
comments Comment[]
setting Setting?
Expand Down Expand Up @@ -1293,6 +1294,49 @@ describe('REST server tests', () => {
});
});

it('creates an item with date coercion', async () => {
const r = await handler({
method: 'post',
path: '/post',
query: {},
requestBody: {
data: {
type: 'post',
attributes: {
id: 1,
title: 'Post1',
published: true,
publishedAt: '2024-03-02T05:00:00.000Z',
},
},
},
prisma,
});

expect(r.status).toBe(201);
});

it('creates an item with zod violation', async () => {
const r = await handler({
method: 'post',
path: '/post',
query: {},
requestBody: {
data: {
type: 'post',
attributes: {
id: 1,
title: 'a very very long long title',
},
},
},
prisma,
});

expect(r.status).toBe(400);
expect(r.body.errors[0].code).toBe('invalid-payload');
});

it('creates an item with collection relations', async () => {
await prisma.post.create({
data: { id: 1, title: 'Post1' },
Expand Down Expand Up @@ -1586,6 +1630,50 @@ describe('REST server tests', () => {
});
});

it('update an item with date coercion', async () => {
await prisma.post.create({ data: { id: 1, title: 'Post1' } });

const r = await handler({
method: 'put',
path: '/post/1',
query: {},
requestBody: {
data: {
type: 'post',
attributes: {
published: true,
publishedAt: '2024-03-02T05:00:00.000Z',
},
},
},
prisma,
});

expect(r.status).toBe(200);
});

it('update an item with zod violation', async () => {
await prisma.post.create({ data: { id: 1, title: 'Post1' } });

const r = await handler({
method: 'put',
path: '/post/1',
query: {},
requestBody: {
data: {
type: 'post',
attributes: {
publishedAt: '2024-13-01',
},
},
},
prisma,
});

expect(r.status).toBe(400);
expect(r.body.errors[0].code).toBe('invalid-payload');
});

it('update a single relation', async () => {
await prisma.user.create({ data: { myId: 'user1', email: 'user1@abc.com' } });
await prisma.post.create({
Expand Down
1 change: 1 addition & 0 deletions packages/server/tests/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ model Post {
author User? @relation(fields: [authorId], references: [id])
authorId String?
published Boolean @default(false)
publishedAt DateTime?
viewCount Int @default(0)

@@allow('all', author == auth())
Expand Down
44 changes: 44 additions & 0 deletions tests/integration/tests/plugins/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,50 @@ describe('Zod plugin tests', () => {
).toBeFalsy();
});

it('does date coercion', async () => {
const { zodSchemas } = await loadSchema(
`
datasource db {
provider = 'postgresql'
url = env('DATABASE_URL')
}

generator js {
provider = 'prisma-client-js'
}

plugin zod {
provider = "@core/zod"
}

model Model {
id Int @id @default(autoincrement())
dt DateTime
}
`,
{ addPrelude: false, pushDb: false }
);
const schemas = zodSchemas.models;

expect(
schemas.ModelCreateSchema.safeParse({
dt: new Date(),
}).success
).toBeTruthy();

expect(
schemas.ModelCreateSchema.safeParse({
dt: '2023-01-01T00:00:00.000Z',
}).success
).toBeTruthy();

expect(
schemas.ModelCreateSchema.safeParse({
dt: '2023-13-01',
}).success
).toBeFalsy();
});

it('generate for selected models full', async () => {
const { projectDir } = await loadSchema(
`
Expand Down