async-local-storage icon indicating copy to clipboard operation
async-local-storage copied to clipboard

Can this be used in api calls?

Open JaiyashreeSM opened this issue 6 years ago • 4 comments

Please carify if this can be used in node APIs where the methods from different files are being called in a single api and should carry some dynamic value throughout the files to be used in all methods.

JaiyashreeSM avatar Dec 18 '18 13:12 JaiyashreeSM

Of course, I'm using it right now to track the request ID propagation throughout the app.

ghost avatar Dec 19 '18 09:12 ghost

@JaiyashreeSM If you don't know how to use async-local-storage, you can show me your codes and I may give you some suggestions.

vicanso avatar Dec 20 '18 02:12 vicanso

@vicanso, We use loopback and here is the simple flow. I get the value being set in the incoming request here in server.js but not carried to test.js The call from rest-client first comes here... server.js `const als = require('async-local-storage');

app.all('*', function(req, res, next) { console.log(Request for --- ${req.method} : ${req.originalUrl}); als.set('reqTenant', req.headers.tenant || 'someTestValue'); next(); });` the control then comes to the file where the api-method is executed

test.js

`const als = require('async-local-storage'); Test.remoteMethod('testAPI', { description: 'Test api', accepts: [], http: {path: '/test', verb: 'get'}, returns: {arg: 'msg', type: 'object', root: true} });

Test.testAPI = (options, callback) => { const searchText = als.get('reqTenant'); Test.find({ where: { name: {ilike: searchText } }, }, (err, res) => { callback(err, res) }); };`

JaiyashreeSM avatar Dec 20 '18 14:12 JaiyashreeSM

@JaiyashreeSM

I am sorry for late replying. You should call the enable function like the example.

vicanso avatar Dec 24 '18 07:12 vicanso