我最近开始在我的nodejs项目中使用typebox。
大多数格式和验证都无法正常工作和编译 像 Type.Strict() -> 不强制执行像 zod 这样的任何严格模式
我尝试添加电子邮件检查格式,但也无法识别
我们是否必须为这些格式另外添加 ajv,但是 ajv-formats 库已被废弃并且 https://www.npmjs.com/package/ajv-formats-draft2019 正在草稿中。
我尝试按照文档不使用 ajv 并添加格式,但它不起作用。
这是根据文档:
You can pass Json Schema options on the last argument of any given type. Option hints specific to each type are provided for convenience.
// String must be an email
const T = Type.String({ // const T = {
format: 'email' // type: 'string',
}) // format: 'email'
// }
// Number must be a multiple of 2
const T = Type.Number({ // const T = {
multipleOf: 2 // type: 'number',
}) // multipleOf: 2
// }
// Array must have at least 5 integer values
const T = Type.Array(Type.Integer(), { // const T = {
minItems: 5 // type: 'array',
}) // minItems: 5,
// items: {
// type: 'integer'
// }
// }
验证:
import { Type, Static } from '@sinclair/typebox';
import { TypeCompiler } from '@sinclair/typebox/compiler';
export const userBSchema = Type.Object({
id: Type.String(),
username: Type.String(),
age: Type.Number({
multipleOf: 2
}),
firstName: Type.String(),
isActive: Type.Boolean(),
email: Type.String({ format: 'email' }),
address: Type.Object({
street: Type.String(),
city: Type.String(),
state: Type.String(),
zipCode: Type.String()
})
});
export const createManyUserBRequestBodySchema = Type.Pick(
userBSchema,
['username', 'age', 'firstName', 'email', 'address'],
{
additionalProperties: false
}
);
export const createManyUserBRequestSchema = Type.Object({
body: Type.Array(createManyUserBRequestBodySchema)
});
export type CreateManyUserBRequestType = Static<typeof createManyUserBRequestSchema>;
用法
async myFUnction(input) => {
try {
const C = TypeCompiler.Compile(createManyUserBRequestSchema);
const isValid = C.Check(input.request);
if (isValid) {
const output = await this.createManyUserUseCase.execute(input.request.body);
return {
message: 'Many User Api Processed Successfully',
result: output
};
}
const all = [...C.Errors(input.request)];
throw new AppError({
name: ApplicationErrorType.VALIDATION_ERROR,
message: JSON.stringify(
all.map((item) => {
return `error is ${item.message}`;
})
),
cause: all
});
} catch (err) {
return {
result: Result.fail<Error>(err)
};
}
}
我的输入是
输入Json
[
{
"username": "alpha_user",
"age": 2,
"firstName": "ALpha",
"email": "[email protected]",
"address": {
"street": "S",
"city": "AMX",
"state": "UK",
"zipCode": "54367"
}
},
{
"username": "beta",
"age": 22,
"firstName": "beta",
"email": "[email protected]",
"address": {
"street": "kotavilla",
"city": "BETA",
"state": "UK",
"zipCode": "54367"
}
},
{
"username": "gamma",
"age": 24,
"firstName": "gamma",
"email": "[email protected]",
"address": {
"street": "kota2villa",
"city": "GAMMA",
"state": "UK",
"zipCode": "54367"
}
}
]
这是错误:
"message": "[\"error is Unknown format 'email'\",\"error is Unknown format 'email'\",\"error is Unknown format 'email'\"]",
电子邮件格式正确仍无法识别
format
关键字默认不执行验证。它一直是描述性/注释性的。
不过,我不确定您正在使用的系统。可能存在启用
format
验证的配置。