Variable scope in javascript module
alweiss
nginx-forum at forum.nginx.org
Tue Oct 30 23:22:28 UTC 2018
Ok, got it !
Thanks much Valentin, Maxim and Dmitry for your guidance.
I decided to go as the nginx sample
(https://www.nginx.com/blog/batching-api-requests-nginx-plus-javascript-module/)
with the resp var which is concatened with result of each subrequest : my
final_status starts with 403 at init time and I add (+=) each subrequest
result so with two subrequest ending in 200, we endup with final_status =
403200200.
At the end of the loop, i call the evaluateStatus function (to make the
evaluation after all subrequests end) to test if final_status contains 200
and we set the res.return(200) or (403) based on that.
Here is the code (i still need to make some cleanup with logging). By the
way, do you have any advice on tuning for better perfs ?
var n = 0;
var final_status = '403';
var servicesCodes = ['rest','oass'];
var requestCount = servicesCodes.length;
function authorize(req, res) {
req.warn('Variables init ...');
function done(reply) { //Callback for completed subrequests ...
n++;
reply.warn('at start of done function, n is : ' + n);
if (n < requestCount) { //| final_status !=200) {
reply.warn('status of subrequest is : ' + reply.status);
if (reply.status == 200) {
reply.warn('lets set final_status to 200');
final_status += '200';
reply.warn('Value of final_status : ' + final_status);
// reply.warn('!!! We return 200 because we have this one at
least, no matter if other are 404 !!!');
// res.return(200);
}
} else { // last response
reply.warn('status of last subrequest is :' + reply.status);
if (reply.status == 200) {
reply.warn('lets set final_status for last subrequest to
200');
final_status += '200';
reply.warn('Value of final_status after last subrequest: ' +
final_status);
} else { // we did not get any 200
reply.warn('!!! We dont insert 200 as we dont have ... ');
reply.warn('Value of final_status after last subrequest: ' +
final_status);
}
// Send the final result
evaluateStatus(final_status);
}
function evaluateStatus(status) {
if (final_status.includes('200')) {
res.return(200)
} else {
res.return(403)
}
}
};
req.warn('n is :' + n);
req.warn('final_status is : ' + final_status);
req.warn('servicesCodes is : ' + servicesCodes);
req.warn('requestCount is : ' + requestCount);
for (var i = 0; i < requestCount; i++) {
req.warn('Entering loop for ' + servicesCodes[i])
req.subrequest("/" + servicesCodes[i] + "/TestDevice1.html", '',
done);
}
}
Posted at Nginx Forum: https://forum.nginx.org/read.php?2,281699,281754#msg-281754
More information about the nginx
mailing list