I have application on Node.js with using Express as API route and MongoDB as DB. I have a raffle. User must join raffle only one time. I am currently using an array in memory with participating, but if you will make two request to API at the same time, user will be joined in raffle two times. How can i disallow to join raffle more than one time?
2 Answers
You should maybe store the array in mondodb, you don't want to loose this list if node restart.
About the "join two time" problem, just throttle the client side function that make the request to your API, so that it can only be called one time during the time passed in your throttle function.
Exemple throttle function :
function throttle (callback, limit) {
var wait = false;
return function () {
if (!wait) {
callback.apply(this, arguments);
wait = true;
setTimeout(function () {
wait = false;
}, limit);
}
}
}
and now your request function :
var throttleApiFunc = throttle(apiFunc, 5000);
// this can only trigger one time each 5 seconds
throttleApiFunc();

- 1,760
- 1
- 12
- 25
-
How avoid to make second user request to one API route while SAME user request is processing? Waiting some time is bad because we have many users. – Aug 07 '16 at 19:31
-
you throttle on the client side so it's not a problem for the user, they won't wait, and throttle don't wait before firing (debounce does), it fire and then you can't fire again the time you said. Since you throttle client side, their won't be two request on the same user processing at the same time, that's exactly what you want. – Gatsbill Aug 07 '16 at 19:55
-
Yes, but some users abusing by sending request from Chrome console ($.post('/api...')) – Aug 07 '16 at 20:00
You would need to structure your workflow to support idempotent operation. That is, performing the same operation twice does not change the result.
For example, incrementing a variable is not idempotent, since calling the increment function twice resulted in the variable get incremented twice (e.g. calling x++
twice will result in adding 2 to x
). I think this is the essence of your current design, where you mentioned: " if you will make two request to API at the same time, user will be joined in raffle two times".
An example of an idempotent operation is setting a variable to a value. For example, calling var x = 1
multiple times will only result in value 1
getting assigned to x
. No matter how many times you call that line, x
will always be 1
.
Some resources to help get you started: