How to make an error for requesting invalid data property on json?

Viewed 9

I want to make an error for requesting invalid data properties on JSON. In the next code, I want to make sure the JSON requesting in valid only if it has a "nombre" property. The condition I implement must have that "nombre" property if(nombre), and that's it. But I also make sure to throw an error if you request another property besides "nombre". Any help is welcome.

This is the function:

export const editarRolInstitucional = async (req: Request, res: Response) => {
try {
    const {id} = req.params;
    const {nombre} = req.body;
    if(nombre){ //El campo nombre esté
        const rolInstitucional = await RolInstitucional.findByPk(id);
        if(rolInstitucional) {
            await rolInstitucional.update({nombre});
            res.status(200).json({
                message: 'El rol institucional ha sido editado con éxito',
                data: rolInstitucional
            });
        } else {
            res.status(400).json({
                message: 'El rol institucional no existe en la base de datos'
            })
        }
    } else {
        res.status(400).json({
            message: 'El campo a editar no es válido'
        })
    }
} catch (e) {
    res.status(400).json({
        message: 'Error al editar el rol institucional',
        error: e
    });
}

}

1 Answers

Assuming what you mean is that you want to verify that req.body is an object with exactly 1 key, nombre, then you can do:

const { nombre } = req.body;
const keys = Object.keys(req.body);

if (keys.length > 1) {
  // handle when something is being sent with the nombre key
} else if (nombre) {
  ...
} else {
  ...
}
Related