*Anyone help please I try to avoid the request if the name exists with NodeJS express *
here is my code
/* Post new person to persons */
app.post("/api/persons/", (req, res) => {
const schema = {
name: Joi.string().alphanum().min(3).max(30).required(),
number: Joi.string().min(9).max(30).required(),
};
const { error } = validateFunction(req.body);
const { body } = req;
const reqValue = persons.some(
(person) => person.name.toLowerCase() === body.name.toLowerCase()
);
if (error) return res.status(400).send(error.details[0].message);
else if (reqValue)
return res.status(409).send(`${body.name} is already exist`);
else {
const person = {
id: persons.length + 1,
name: req.body.name,
number: req.body.number,
};
I solved the issue:
/* Post new person to persons */
app.post("/api/persons/", (req, res) => {
const schema = {
name: Joi.string().exist().alphanum().min(3).max(30).required(),
number: Joi.string().min(9).max(30).required(),
};
const { body } = req;
const { error } = validateFunction(body, schema);
const result = persons.filter(({ name }) => name === body.name);
console.log("resulit", result);
console.log("The name of request", body.name);
if (error) return res.status(400).send(error.details[0].message);
else if (result && result.length > 0) return res.status(409).send(`${body.name} is already exist`);
else {
const person = {
id: persons.length + 1,
name: req.body.name,
number: req.body.number,
};
persons.concat(person);
res.send(person);
}
});