Tell me how to do the validation and what libraries do you use?

For example, I have a model category with 2 name and url fields. name and url cannot be empty and url unique field.

I have a controller that gets the required fields from the request and sends them to the categoryService service, I did it this way, maybe there is some better way:

  async createCategory (data) { const errors = saveCategoryValidation(data) if (Object.keys(errors).length) { const error = new Error('invalid category data') error.errors = errors throw error } const category = await knex('categories').insert(data) return category }, 

saveCategoryValidation:

 export default async (data) => { const messages = {} if (_.isNil(data.name) || !data.name.length) { messages.name = 'Name is required' } if (_.isNil(data.url) || !data.url.length) { messages.name = 'Name is required' } else { const categories = await knex('categories') .select('id') .where('url', data.url) if (categories.length) { messages.url = 'Url already in use' } } return messages } 
  • Maybe it is better to screw the validation somehow into the controller? - Roman C
  • "url is a unique field." I would just sew in the database schema and, if I add an error, I would suggest correcting, checking for empty fields hex: if (data.name) - sair

0