Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Is there a way to use callback functions in joi validation?

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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,
    })
  );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda