2

I'm attempting to store an ID in continuation-local-storage so I can output it in the logs after a successful gRPC request. I create the namespace at the start of the app then set the ID in middleware (in the full implementation the ID will come in in the request). I then attempt to get the ID in a get('/'). Getting the ID works but I'm then unable to get it inside the gRPC request:

app.js

const cls = require('continuation-local-storage');
cls.createNamespace("THING");
var express = require('express');
var path = require('path');
var index = require('./routes/index');
var app = express();

const storeRequestId = (req, res, next) => {
  const ns = cls.getNamespace("THING");
  ns.run(() => {
    ns.set('thing-id', '123');
    next();
  });
}
app.use(storeRequestId);

app.use('/', index);

module.exports = app;

index.js

const cls = require('continuation-local-storage');
var express = require('express');
var router = express.Router();
var grpc = require('grpc');
const path = 'path/to/proto'
const rootPath = 'root/path'
console.log({root: rootPath, file: path})

const identityService = grpc.load({root: rootPath, file: path}).identity.service;
const grpcCredentials = grpc.credentials.createInsecure();
const identityClient = new identityService.Identity('localhost:8020', grpcCredentials)

/* GET home page. */
router.get('/', function(req, res, next) {
  ns = cls.getNamespace('THING');
  console.log(ns.get('thing-id'));

  const retrievePartyReq = {
    party_id: 'party123',
  }

  identityClient.retrieveParty(retrievePartyReq, (err, response) => {
    ns = cls.getNamespace('THING');
    console.log(ns.get('thing-id'));
  })

  res.status(200).send('200: All is good.');
});

module.exports = router;

This outputs in the logs:

123
undefined

Where I would expect 123 both times. Why can't I grab the value from the namespace from within the gRPC request?

user285429
  • 303
  • 1
  • 4
  • 10

1 Answers1

1

I decided to switch to cls-hooked instead. That fork of continuation-local-storage seems to work better. Just make sure your node version is >= 9.

user285429
  • 303
  • 1
  • 4
  • 10