Home > Software engineering >  Pass value from request directly to an api call in express
Pass value from request directly to an api call in express

Time:11-28

I have an express application that I didn't write. Simply the app takes params, calls a cms api with them and it builds dynamically a page using handlebars which it sends in a response.

In the request I get a JWT token in a cookie and I need to pass it to every api call now.

The logic is however quite extensive and there are lot of functions called between the app.get() and the final function getFromBackend that makes the api call and needs the jwt token. There are also many implementations of it in async handlebars helpers etc.

So I was wondering if I do have to pass the value through all of the functions that are called between app.get and the getFromBackend and in the helpers that make api calls. Or if there is a pattern that would allow me to use the value of the request cookie inside the function directly or maybe interject the api call and pass the value to the call.

Considering especially that all of the api calls that are made for the req will always have the same jwt token. There are several api calls happening for each req but all of them implement the getFromBackend function.

CodePudding user response:

It's kind of hard to know what your options are without seeing the actual code. Folks could offer you more specific help if you showed the real code.

Absent specific code, the general options available to you are:

  1. Put the parsed token as a property on some object that is getting passed all the way through to the end (such as the Express response object). The end of the chain usually has to send a response so it will have to have access to that response object anyway.

  2. Put the parsed token in a higher scoped variable (within the request handler scope) that is available from that higher scope for most of the way and then pass it at the end whenever calling something that can't access it from that scope.

  3. Pass the token by itself all the way through to the end.

  4. Convert to an object oriented design so that most or all of the functions involved in processing this request are methods on an object and you can make the parsed token be an instance variable on an object that all the methods hang off of. Then, every one of these methods can get access to the token via this.token or something like that.

CodePudding user response:

If the cms api call is made in the same request response cycle then best attach it to the response object and use it for the cms api call.

if that is not straight fwd or if the cms call is in some other request response cycle, you can use redis or any in-memory db to store the jwt token and retrieve it for the cms api call.

  • Related