Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
¿Hay alguna forma de usar las funciones de devolución de llamada en la validación de joi?

su gurú

Estoy investigando un código que vi en Internet, pero si veo la sintaxis, han usado Hapi/Joi, que está en desuso. Mi pregunta es ¿cómo puedo usar esta sintaxis en 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) }); } }); });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Al inspeccionar el archivo de tipos ( index.ds.ts ) en Github , de hecho, no hay una función de validate de estilo de devolución de llamada, solo esos dos métodos:

 /** * 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>;

Sin embargo, puede usar util.callbackify - ejemplos de devolución de llamada para transformar validateAsync en un estilo de nodo de devolución de llamada si realmente desea:

 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), }); });

Usaría lo que proporciona Joi , como en los siguientes 2 ejemplos:

 // 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, }); }

O incluso con solo promesas:

 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, }) );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!