E
E
Eggziom2021-03-28 11:18:34
Validation
Eggziom, 2021-03-28 11:18:34

How to organize data validation in API?

I am writing a pet project, I have a question about api (it's on the express node, but it's probably not the point) - or rather, about validation.
The request goes through a series of middlewares:

router.delete(
    "/:id",
    middlewares.isAuthed,
    schemaValidation.deletePost, // проверяю поступающие данные
    dataValidation.deletePost, // проверяю, согласуются ли поступающие данные с записями в БД
    controllers.deletePost // передаю данные в метод соотв. сервиса
);

So, there is, say, a request - to delete a post by id. At the dataValidation stage, I access the database and see if there is such a post at all. If there is no post, I immediately give 404. Otherwise, the request goes further, and then the service again accesses the database - this time to delete the record. It looks like an extra step is being performed during the validation step. It, of course, searches on primary key, but nevertheless.
What should be done in such cases? Maybe even remove the check for the existence of a post from such a route? Like, the delete method itself will return null / false, and let the controller interpret this as 404?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question