通过检查Github中的类型(index.ds.ts)文件,确实没有回调样式validate函数,只有这两种方法:
/**
* Validates a value using the schema and options.
*/
validate(value: any, options?: ValidationOptions): ValidationResult;
/**
* Validates a value using the schema and options.
*/
validateAsync(value: any, options?: AsyncValidationOptions): Promise<any>;
但是,如果您真的想要,可以使用util.callbackify - callbackify examples 将validateAsync 转换为回调节点样式:
const Joi = require('joi');
const { callbackify } = require('util');
// A very simple data object
const obj = { a: 23 };
// A very simple joi schema which checks if schema is an object with the `a` property being a string
const schema = Joi.object({
a: Joi.string(),
});
// Callback style (which i don't recommend since its not available in `joi` package)
callbackify(() => schema.validateAsync(obj))((err, ret) => {
if (err) {
return res.status(400).json({
status: 'error',
message: 'Invalid request data',
data: data,
});
}
res.status(200).json({
status: 'success',
message: 'User created successfully',
data: Object.assign({ id }, value),
});
});
我会使用 Joi 提供的内容,如以下 2 个示例:
// using async/await - you need to mark you controller as async, like:
// app.post('/test', async (req, res, next) => ...
try {
await schema.validateAsync(obj);
res.status(200).json({
status: 'success',
message: 'User created successfully',
data: Object.assign({ id }, value),
});
} catch (err) {
res.status(400).json({
status: 'error',
message: 'Invalid request data',
data: data,
});
}
甚至只是承诺:
schema
.validateAsync(obj)
.then(() =>
res.status(200).json({
status: 'success',
message: 'User created successfully',
data: Object.assign({ id }, value),
})
)
.catch(() =>
res.status(400).json({
status: 'error',
message: 'Invalid request data',
data: data,
})
);