参数校验
校验
Midway Hooks 使用 zod@3 作为校验器,并提供 Validate(...schemas: any[])
校验用户入参,ValidateHttp(options)
函数来校验 Http 结构。
使用前请安装 zod。
npm install zod
Validate
Validate
传入的 Schema 顺序与用户入参顺序匹配。
基础示例
import {
Api,
Post,
Validate,
} from '@midwayjs/hooks';
import { z } from 'zod';
export default Api(
Post('/hello'),
Validate(z.string(), z.number()),
async (name: string, age: number) => {
return `Hello ${name}, you are ${age} years old.`;
}
);
一体化调用:
import hello from './api';
try {
await hello(null, null);
} catch (error) {
console.log(
JSON.parse(error.data.message)
);
console.log(error.status); // 422
}
手动调用:
fetcher
.post('/hello', {
args: [null, null],
})
.catch((error) => {
console.log(
JSON.parse(error.data.message)
);
console.log(error.status); // 422
});