2016-04-01 4 views
0

ユーザーがWebページのユーザーの選択に基づいてダウンロードするファイルを提供するエンドポイントがあります。しかし、ユーザーの選択の可能性に基づいて、私が考えることができるのは、if/elseステートメントを使用することだけです。if/elseの代わりにnodejsサーバー上でファイルを提供するためのより良い方法

router.post('/process', function(req, res) { 
    if(req.query.os == 'Windows' && req.query.rec == 'Computer Information' && req.query.report == 'Local Report') { 
     res.send('http://localhost:3033/proc/windows/info/local/files.zip'); 
    } else if (req.query.os == 'Windows' && req.query.rec == 'User Information' && req.query.report == 'Local Report') { 
     res.send('http://localhost:3033/proc/windows/uinfo/local/files.zip'); 
    } 
} 

私はLinuxやOSX用のオプションを追加した場合は、病気の結果として、コードは非常に長く、醜いとなり、同様にそれらを考慮する必要があります。私がこれを説明する良い方法はありますか?

答えて

0

変数をURLパーツに変換します。維持しやすくなります。例:

router.post('/process', function(req, res) { 
    var url_parts = { 
     'os' : { 
      'Windows' : 'windows', 
      'Linux' : 'linux', 
      'OSX' : 'mac' 
     }, 
     'rec' : { 
      'Computer Information' : 'info', 
      'User Information' : 'uinfo' 
     }, 
     'report' : { 
      'Local Report' : 'local', 
      'Global Report' : 'global' 
     } 
    }; 

    res.send(
     'http://localhost:3033/proc/' 
     + url_parts.os[req.query.os] 
     + '/' + url_parts.rec[req.query.rec] 
     + '/' + url_parts.report[req.query.report] 
     + '/files.zip' 
     ); 
}); 
関連する問題