So I'm creating a REST API, and when someone calls a method to return data I get the data from an external API, check if the ID of the data already exists and if it does, update it, and if not create it.
The problem is that if another request were to come in for the same resource, my function looks up the data, and finds that it does not exist (yet), however by the time it's got to the save call, the save from the previous function has completed, so the save fails (some fields must be unique).
I've currently setup a queue using nodejs async and a single worker. This works however I think it's really going to cause performance issues!
Does anyone know how I can do this in a way thats not going to cause performance issues?
var storeData = function(APIResponse, id, callback){
Record.findOne({ id: id }, function(err, data) {
if(data === null) {
//No record, so lets create one
var data = {};
data.id = id;
data.title = APIResponse.title;
var dataToSave = new Record(data);
} else {
//data exists in store, lets update it
data.title = APIResponse.title; //Update title
var dataToSave = data;
}
dataToSave.save(function(err, doc) {
if(err) {throw err;}
//A callback to continue with some other processes
callback(null, APIResponse, doc);
});
});
};
Any ideas/suggestions would be really appreciated, Many Thanks