I'm building a server using only nodeJS libraries and methods but I'm having trouble checking the request body format and responding right away with a client error status code type (400-499).
The following code is of a js file of a controller for a type of request supported by my server (I'm using an MVC type architecture):
const { createNews } = require('../useCases/postNewsUseCase'); //useCase file to which the request proceeds if its in good format
const postNews = (req, res) => {
if (req.method !== 'POST') { //tests if request method is correct
res.writeHead(405, { 'Contet-type': 'text/plain' });
res.end();
}
let data = '';
req.on('data', chunk => {
data += chunk;
})
req.on('end', () => {
const newsBody = JSON.parse(data);
if (Object.keys(newsBody).toString() !== ['title','content','category'].toString()){
res.writeHead(400, { 'Contet-type': 'text/plain' });
res.end();
} // tests if the request body format matches the expected
for (let field in newsBody) {
if ((/^\s*/).test(newsBody[field])){
res.writeHead(400, { 'Contet-type': 'text/plain' });
res.end(); // tests if any property is not provided/blank
}
}
createNews(newsBody); //sends the request to the next level which will interact with the DB
res.end();
});
}
module.exports = {
postNews
}
The thing is, if a request body like the following (bad format) is sent, the server proceeds to the useCase level anyway instead of ending the communication between client and server as specified in my tests:
{
"title":"titulo",
"content":"conteudo"
}
Can anyone help me? Am I misusing res.end() to end communication and returning the server response?
You can use Joi library. https://github.com/sideway/joi
example of use.
{
"title": "This is supposed to be a title",
"content": "There should be some content here."
}
const schema = Joi.object({
title: Joi.string().min(8).max(30).required(),
content: Joi.string().min(24).max(255).required(),
});