0

I need to decrypt some buffers which I retrieve from my MySQL database to get a string I need to use in various places in my node.js Express module.

I can call this function everytime when I need the string however this string after being decrypted will always be the same hence calling this function everytime is not ideal as round trip to database and time to decrypt.

I can declare this as a global variable, call the function and assign to value to the global variable, or I come across this article setting this string to a process.env variable.

What's the best practise I can apply here?

Using global variable seems to me is not advisable as it can be overwritten somewhere else though chances are slim in my case.

Steven Yong
  • 5,163
  • 6
  • 35
  • 56

2 Answers2

1

I have found this article about it, but I didn't have a chance to try it: https://thoughts.travelperk.com/optimizing-js-with-lazy-evaluation-and-memoization-9d0cd8c30cd4

  • Looks like memoization is possible! https://scotch.io/tutorials/understanding-memoization-in-javascript/amp – Steven Yong Jul 30 '20 at 11:44
  • Quite cool, for anyone who is interested and hopefully it helps someone, I managed to do this using this component: npmjs.com/package/fast-memoize – Steven Yong Jul 30 '20 at 14:17
1

You can inject the value into req object at the routing page.

This way modification can only be done at the routing.

Changes can be done as well (only by the routing module page,whatever is call).

app.use("/this will not get scret string",route)


app.use((req,res,next)=>{
  req.yourSecretString = secreString;
})


app.use("/this will  get scret string",route)

app.use((req,next,err)=>{res.status(404).end()})https://stackoverflow.com/posts/63172199/edit#
AnonyMouze
  • 416
  • 2
  • 7
  • this is useful which is something I am not aware of, but my question is secreString needs to be assigned via a function call and every routes will get this even though routes I do not need this secreString? – Steven Yong Jul 30 '20 at 11:41
  • 1
    yes ,every route will get it or you can assign route which will get it after this statement. i will update the snippet – AnonyMouze Jul 30 '20 at 12:14