I have a route on an express server that has to call an external API that sends back a list of files on that server. Afterwards you call another one of its APIs to get the contents of each file. Once I have that, I write the contents of each file to a new file in my project's root directory.
That's all fine and works good. The problem is when I do it with more than one user. This request takes about 3 minutes to complete, and if it's just one instance of my app calling the route then it works fine every time. But if I open another instance, log in with another user and start the same request at the same, I run into issues.
It's not a timeout issue, although I have dealt with that while working on this and already found ways around that. This definitely has to do with multiple users hitting the route at once.
Sometimes it doesn't complete at all, sometimes it quickly throws an error for both users, and sometimes just one will fail while the other's completes.
I've been looking around, and I suspect that I'm blocking the event loop and need to use something like worker threads. My question is am I on the right track with that or is it something else I don't know?
The code basically looks like this:
//this whole request takes about 3 minutes to complete if successful due to rate limiting of the external APIs.
//it's hard to imagine why I would want to do this kind of thing, but it's not so important.. what is really important
//is why I get issues with more than 1 user hitting the route.
router.get('/api/myroute', (req, res, next) => {
//contact a remote server's API, it sends back a big list of files.
REMOTE_SERVER.file_list.list(USER_CREDS.id).then(files => {
//we need to get the contents of each specific file, so we do that here.
Promise.all(files.map((item, i) =>
//they have an API for specific files, but you need the list of those files first like we retrieved above.
REMOTE_SERVER.specific_file.get(USER_CREDS.id, {
file: { key: files[i].key }
}).then(asset => {
//write the contents of each file to a directory called "my_files" in the project root.
fs.writeFile('./my_files/' + file.key, file.value, function (err) {
if (err) {
console.log(err);
};
});
})))
.then(() => {
console.log("DONE!!");
res.status(200).send();
})
});
});