Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a header parameter with Joi, nodejs?

I want to check one parameter (docsLimit in this case) of a header of a HTTP request. So i did this:

const {
  celebrate,
  Joi,
} = require('celebrate');
const joiObjectId = require('joi-objectid');

Joi.objectId = joiObjectId(Joi);

const limit = celebrate({
  headers: Joi.object().keys({
    docsLimit: Joi.number()
      .required()
      .default(10),
  }).options({ allowUnknown: true })
});

module.exports = limit;

in app.js:

app.get(path, limit, getDocuments);

I have to say that I am new to nodejs and especially Joi but that seems to have sense to me. That is wrong instead, because if I send a string in the headers it accepts it anyway, even if I precised it to be a number. If I remove the .options({ allowUnknown: true }) then it never passes, even there's a number. It says "UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" and returns a json saying that "limit is not allowd". Which is the way to check a parameter in headers with Joi?

Thank you very much!


1 Answers

The problem is that the header is always a string so I shouldn't do Joi.number(). I should use Joi.string() and after that, I check with a regex in order to be a number. Finally I convert it into a number before using it!


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!