0

I am currently creating an API for posting in backend with nodejs. My data object, which gets provided from the frontend contains multiple objects.

My first step is to check if these multiple consts are empty and if they are, they give specific error messages, which looks like this:


//constants
  const { name, lang, email  } = req.body;
 
  if (!name) {
    return res.status(400).json({
      error_code: 1,
      message: 'Missing name',
    });
  }

  if (!lang) {
    return res.status(400).json({
      error_code: 2,
      message: 'Lang not provided',
    });
  }

if (!email) {
  return res.status(400).json({
    error_code: 3,
    message: 'email is not provided',
  });
}

In the example above there are only three parameters but how would it look for much more constants? I thought about doing a switch ... case but I am not sure if that is the best solution and how exactly that would look like.

Do you guys have any experience or suggestions?

3
  • Do you just need a distinctive message for each missing/invalid/... property, or do you also need a distintive error_code? What result do you expect if multiple properties are invalid/missing? Commented Oct 18, 2022 at 9:35
  • 1) yea i need a distinctive message for each inidividual property Commented Oct 18, 2022 at 12:09
  • 2) like an overall error, like please input in missing textfields. If only one error eccoured, send specific error message to frontend Commented Oct 18, 2022 at 12:11

1 Answer 1

0

Consider using data validator libraries like ajv or joi which are designed for such purpose.

For instance, with joi you can have something like this:

const Joi = require('joi');

const schema = Joi.object({
  name: Joi.string()
    .min(3)
    .max(30)
    .required(),
  lang: Joi.string()
    .min(2)
    .required(),
  email: Joi.string()
    .email({
      minDomainSegments: 2,
      tlds: {
        allow: ['com', 'net', 'org']
      }
    })
})

// then in your controller you can have something like this
schema.validate(req.body);
// or this (I prefer this one)
try {
  const value = await schema.validateAsync(req.body);
} catch (err) {
  // do something
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thx for you response. I use joi for my models in backend. So you would suggest to use joi in the api itself?
Definitely, it makes sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.