I've hit a really strange issue, with Node & Express.
I have a middleware function, which can either be invoked in three different ways:
app.get('/', auth, handler)
app.get('/', auth('role'), handler)
app.get('/', auth('role', 'scope'), handler)
The obvious way to do this would be like this:
exports.auth = (a, b, c) => {
let role, scope;
switch(arguments.length) {
case 3:
// Called directly by express router
handleAuth(a, b, c);
break;
case 2:
case 1:
// Called with role/scope, return handler
// but don't execute
role = a;
scope = b;
return handleAuth;
}
function handleAuth(req, res, next) {
// Do some custom auth handling, can
// check here if role/scope is set
return next();
}
}
However, I'm getting some very odd results for arguments.length. When called in the 2nd way, arguments.length == 5, and none of the arguments is role.
[ '0': '[object Object]',
'1': 'function require(path) {\n try {\n exports.requireDepth += 1;\n return mod.require(path);\n } finally {\n exports.requireDepth -= 1;\n }\n }',
'2': '[object Object]',
'3': '/Users/redacted/auth/index.js',
'4': '/Users/redacted/auth' ]
If I log a, b, c within the function, I get a: 'role', b: undefined, c: undefined.
I've tried to reproduce it in Runkit, but haven't had any luck: https://runkit.com/benedictlewis/5a2a6538895ebe00124eb64e