Their Guru's
I'm doin a research on a code I saw on the internet, but if I see the syntax, they have used Hapi/Joi which is depricated. My question is how can I use this syntax in Joi?
app.post('/test', (req, res, next) => {
const id = Math.ceil(Math.random() * 9999999);
Joi.validate(data, schema, (err, value) => {
if (err) {
res.status(400).json({
status: 'error',
message: 'Invalid request data',
data: data
});
} else {
res.status(200).json({
status: 'success',
message: 'User created successfully',
data: Object.assign({id}, value)
});
}
});
});
By inspecting the types (index.ds.ts) file in Github indeed there is no callback style validate function, only those two methods:
/**
* 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>;
However you can use util.callbackify - callbackify examples to transform validateAsync into a callback node style if you really want to:
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),
});
});
I would use what Joi provide, as in the following 2 examples:
// 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,
});
}
Or even with just promises:
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,
})
);