GLOBAL data per HTTP/Session request?

前端 未结 5 2221
刺人心
刺人心 2021-01-05 23:56

QUESTION:

Is there any way to create a variable storage in per session/http request? The variable must be globally accessible and different

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 00:21

    Per request, I think what you're after could be done with ordinary closures. For example, you'd define your custom functions in module that takes a req argument:

    util_funcs.js:

    module.exports = function( req ){
      return {
        customFunctionThatRequiresReq: function(){ console.info( req ) },
        otherFunctionThatRequiresReq:  function(){ console.log( req ) }
      };
    };
    

    Then wherever you depend on those functions (presumably some middleware elsewhere in the application), you can just require them in context:

    var someMiddleWare = function( req, res, next ){
    
      var utils = require( 'util_funcs.js' )( req );
    
      utils.customFunctionThatRequiresReq();
      utils.otherFunctionThatRequiresReq();
    
    }; 
    

    This allows you to avoid littering your function args with req, and no dubious globals.

提交回复
热议问题