静态类型安全 + 运行时安全
使用 Prisma 和 @midwayjs/hooks
提供的 Validate 校验器, 可以实现从前端到后端再到数据库的类型安全 + 运行时安全链路。
以 hooks-prisma-starter 中的 POST /api/post
接口为例,代码如下:
import {
Api,
Post,
Validate,
} from '@midwayjs/hooks';
import { prisma } from './prisma';
import { z } from 'zod';
const PostSchema = z.object({
title: z.string().min(1),
content: z.string().min(1),
authorEmail: z.string().email(),
});
export const createPost = Api(
Post('/api/post'),
Validate(PostSchema),
async (
post: z.infer<typeof PostSchema>
) => {
const result =
await prisma.post.create({
data: {
title: post.title,
content: post.content,
author: {
connect: {
email: post.authorEmail,
},
},
},
});
return result;
}
);