[Typescript] Create a Type-Safe Request Handler with Zod and Express
import express, { RequestHandler } from 'express';
import { it } from 'vitest';
import { z, ZodError } from 'zod';
import { Equal, Expect } from '../helpers/type-utils';
import { ParsedQs } from 'qs';
const makeTypeSafeHandler = <
TQuery extends ParsedQs = any,
TBody extends Record<string, any> = any
>(
config: {
query?: z.Schema<TQuery>;
body?: z.Schema<TBody>;
},
handler: RequestHandler<any, any, TBody, TQuery>
): RequestHandler<any, any, TBody, TQuery> => {
return (req, res, next) => {
const { query, body } = req;
if (config.query) {
try {
config.query.parse(query);
} catch (e) {
return res.status(400).send((e as ZodError).message);
}
}
if (config.body) {
try {
config.body.parse(body);
} catch (e) {
return res.status(400).send((e as ZodError).message);
}
}
return handler(req, res, next);
};
};
const app = express();
it('Should make the query AND body type safe', () => {
app.get(
'/users',
makeTypeSafeHandler(
{
query: z.object({
id: z.string(),
}),
body: z.object({
name: z.string(),
}),
},
(req, res) => {
type tests = [
Expect<Equal<typeof req.query, { id: string }>>,
Expect<Equal<typeof req.body, { name: string }>>
];
}
)
);
});
it('Should default them to any if not passed in config', () => {
app.get(
'/users',
makeTypeSafeHandler({}, (req, res) => {
type tests = [
Expect<Equal<typeof req.query, any>>,
Expect<Equal<typeof req.body, any>>
];
})
);
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-03-02 [SCSS] SCSS and CSS Variables
2020-03-02 [Github] Create a GitHub PR Template
2020-03-02 [Github] Create a GitHub Issue Template
2017-03-02 [SVG] Combine Multiple SVGs into an SVG Sprite
2017-03-02 [Ramda] Difference between R.converge and R.useWith
2017-03-02 [Ramda] Refactor to a Point Free Function with Ramda's useWith Function
2017-03-02 [Angular] Dynamic component's instance and sorting