2017-12-08 7 views
0

私は本当に奇妙な問題を襲ってきたの異なるオブジェクト。引数は、ノード& Expressで、引数

私は3つの異なる方法で呼び出すことができますいずれかのミドルウェア機能、持っている:私は、しかし

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(); 

    } 
} 

:これを行うには明白な方法は次のようになります

app.get('/', auth, handler) 
app.get('/', auth('role'), handler) 
app.get('/', auth('role', 'scope'), handler) 

arguments.lengthの非常に奇妙な結果が得られました。第2の方法で呼び出されたときは、arguments.length == 5であり、引数のいずれも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' ] 

私は関数内a, b, cをログインした場合、私はa: 'role', b: undefined, c: undefinedを取得します。

私はは、runkitでそれを再現しようとしたが、任意の運を持っていなかった。https://runkit.com/benedictlewis/5a2a6538895ebe00124eb64e

答えて

1

arguments矢印機能(() =>)に露出していません。必要な場合は、代わりに通常の関数を使用してください。

exports.auth = function(a, b, c) { 

    let role, scope; 

    switch(arguments.length) { 
    ... 

サイドノートargumentsあなたのその矢印の機能は、実際に各モジュール/必要なコードを実行中のNode.jsが使用するラッパー関数から選ばれるにはを参照してください。この関数を使用すると、exportsrequiremodule__dirname__filenameなどの「魔法のような」変数にアクセスできるため、5引数が表示されます。

0

私はcaseが壊れていると思います。

'use strict'; 
let express = require('express'); 
let app = express(); 

//app.get('/', auth, handler); 
app.get('/', auth('role'), handler); 
//app.get('/', auth('role', 'scope'), handler); 

function auth (a, b, c) { 
    let role; 
    if (a == 'role') { 
     role = 'user'; 
     return handleAuth; 
    } 

    if (a != 'role')   
     return handleAuth(a, b, c); 

    function handleAuth(req, res, next) { 
     console.log(role || 'guest'); 
     next(); 
    } 
} 

function handler (req, res, next) { 
    res.send('OK'); 
} 

app.listen(3000,() => console.log('Listening on port 3000')); 

P.S. Imho、このコードは結構です。