Monday, 15 May 2017

Passing context implicitly across functions and javascript files in nodes.js

I have created a web server i node.js using express and passport. It authenticates using an oauth 2.0 strategy (https://www.npmjs.com/package/passport-canvas). When authenticated, I want to make a call such as:

app.get("/api/courses/:courseId", function(req, res) {
  // pass req.user.accessToken implicitly like 
  // through an IIFE
  createExcelToResponseStream(req.params.courseId, res).catch(err => {
    console.log(err);
    res.status(500).send("Ops!");
  });
});

My issue is that i would like, in all subsequent calls from createExcelToResponseStream, to have access to my accessToken. I need to do a ton of api calls later in my business layer. I will call a method that looks like this:

const rq = require("request");    
const request = url => {
  return new Promise(resolve => {
    rq.get(
      url,
      {
        auth: {
          bearer: CANVASTOKEN // should be req.user.accessToken 
        }
      },
      (error, response) => {
        if (error) {
          throw new Error(error);
        }
        resolve(response);
      }
    );
  });
};

  • If i try to create a global access to the access token, i will risk race conditions (i think) - i.e. that people get responses in the context of another persons access token.
  • If i pass the context as a variable i have to refactor a lof of my code base and a lot of business layer functions have to know about something they don't need to know about

Is there any way in javascript where i can pass the context, accross functions, modules and files, through the entire callstack (by scope, apply, bind, this...). A bit the same way you could do in a multithreaded environment where you have one user context per thread.



via Rasmus Knap

No comments:

Post a Comment