A
A
Alexey Shevchenko2019-11-14 13:37:26
MongoDB
Alexey Shevchenko, 2019-11-14 13:37:26

How to correctly handle a double request to the API and MongoDB on the server?

There is a task:
When requesting a server on express.js, look for data on a third-party API and issue it to the user. At the same time, when making a request, it is necessary to check if this record exists in the MongoDB database, and if not, then create it.
While there is only one parameter with one value in the req.query request, the algorithm looks simple:
1. Send the request.
2. Using the received data, search for a record in the database.
3. If there is no record - create and send to the user, if there is - send the found one.
But the requirements of the task are such that the parameter can contain two values. Then the algorithm, taking into account the asynchrony of the code, becomes much more complicated and contains many duplicate operations (at least in my implementation):
1. Send a request for the first value.
2. Search in the database.
3. If not found, then create.
4. Send a request for the second value and repeat steps 2 and 3.
5 Return the result with both records.
In code, it looks like a hash of if else and also a bunch of promises.
Is there a better solution that I'm missing and where can I read about it?

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