[Typescript] Create a Type-Safe Request Handler with Zod and Express
typescript and with type create request Express handler
2023-09-14 08:59:11 时间
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>>
];
})
);
});
相关文章
- typescript快速入门
- typescript web_typescript在线运行
- TypeScript(3)基础类型[通俗易懂]
- NextJS x Typescript - Integration & Troubleshooting
- Typescript 4.9重点特性探索
- TypeScript 实用工具类型之 Partial 类型
- TypeScript-tsx文件webstorm无法识别alias配置解决方法
- TypeScript泛型应用
- 解释器模式举例-TypeScript 类型体操天花板,用类型运算写一个 Lisp 解释器
- 软件开发入门教程网之TypeScript 类
- 一道 3 层的 TypeScript 面试题,你能答到第几层?
- TypeScript 新语法 satisfies:用声明还是用推导?这是个问题
- 开发者数量2025年预计破亿,TypeScript受欢迎度飙升:GitHub最新年度报告
- 开心档之TypeScript 变量声明
- ORA-39322: Cannot use transportable tablespace with TIMESTAMP WITH TIME ZONE columns and different time zone version. ORACLE 报错 故障修复 远程处理
- 多条件查询MySQL中使用And多条件查询的步骤(mysql中and)
- 深入浅出:MySQL中AND和OR运算符使用方法(mysql中and和or)
- Oracle数据库中的AND查询(oracle and查询)
- Oracle中使用AND运算符的示例分析(oracle中and用法)
- TypeScript 4.4 RC 发布