H
HonoWAAYZZz 🍀

Type checking with Hono + prisma + zod -> return json date (expect string)

HI, i m usin openAPi I declared return params in my route
const getUserRoute = createRoute({
method: 'get',
path: '/',
responses: {
200: {
description: 'Respond after getting his user',
content: {
'application/json': {
schema: schema: z.object({
id: z.string(),
email: z.string(),
username: z.string(),
createdAt: z.coerce.date(),
lastLoginOn: z.coerce.date(),
}),
},
},
},
404: {
description: 'User not found',
content: {
'application/json': {
schema: ErrorSchema,
},
},
},
},
});

app.openapi(getUserRoute, async (c) => {
const id = c.get('id');
const user = await getUser({ id });
if (user) {
return c.json({
id: user.id,
email: user.email,
username: user.username,
createdAt: user.createdAt,
lastLoginOn: user.lastLoginOn,
});
}
return c.json({
error: 'User not found',
}, 404);
const getUserRoute = createRoute({
method: 'get',
path: '/',
responses: {
200: {
description: 'Respond after getting his user',
content: {
'application/json': {
schema: schema: z.object({
id: z.string(),
email: z.string(),
username: z.string(),
createdAt: z.coerce.date(),
lastLoginOn: z.coerce.date(),
}),
},
},
},
404: {
description: 'User not found',
content: {
'application/json': {
schema: ErrorSchema,
},
},
},
},
});

app.openapi(getUserRoute, async (c) => {
const id = c.get('id');
const user = await getUser({ id });
if (user) {
return c.json({
id: user.id,
email: user.email,
username: user.username,
createdAt: user.createdAt,
lastLoginOn: user.lastLoginOn,
});
}
return c.json({
error: 'User not found',
}, 404);
my prisma schema generating
model User {
id String @id @default(cuid())
email String @unique /// @zod.string.email({ message: 'Invalid email address' }),
username String @unique
password String
isEmailValided Boolean
createdAt DateTime @default(now())
lastLoginOn DateTime?
plans UserWithPermissions[]
passwordForgotten PasswordForgotten[]
}
model User {
id String @id @default(cuid())
email String @unique /// @zod.string.email({ message: 'Invalid email address' }),
username String @unique
password String
isEmailValided Boolean
createdAt DateTime @default(now())
lastLoginOn DateTime?
plans UserWithPermissions[]
passwordForgotten PasswordForgotten[]
}
But since the json return transform date to string, type checking is wrong. What is the best thing to do to handle that ? (the return schema is generated by zod-prisma-types) it's look easy but i m new with zod and openApi If i change z.coerce.date() to z.string() type checking will work, but thoz zod object is auto generated by zod-prisma-types
D
DoggeSlapper14d ago
It's related to zod. Use z.string().datetime()