skonves / express-http-context

Get and set request-scoped context anywhere
MIT License
299 stars 26 forks source link

Context is lost sometimes during one request #29

Closed dvneverov closed 5 years ago

dvneverov commented 5 years ago

I've noticed very strange behavior of library. I make several requests to external API during 1 request to my own and I want to write logs of each external request into DB. Before each request I'm trying to get the ID of current document which was set in context. But sometimes this value is undefined and sometimes not.

const request = require('request');
const mongoose = require('mongoose');
const httpContext = require('express-http-context');
const PolicyLog = mongoose.model('PolicyLog');

const updatePolicyLog = (id, log) => {
  return new Promise((resolve, reject) => {
    PolicyLog.update({ "policyId": mongoose.Types.ObjectId(id) },
      { $push: { logs: log } }
    ).then(() => {
      resolve();
    }).catch(err => {
      reject(err);
    });
  });
};

exports.createPolicy = (policy) => {
  return new Promise((resolve, reject) => {
    // prepare request body and do some other stuff here

    let options = {}; // request options (url, method, headers & body)
    request(options, (error, response, body) => {
      if (error)
        reject(error);

      let policyLocalId = httpContext.get("policyLocalId");
      console.log(policyLocalId)  // sometimes it's undefined
      updatePolicyLog(policyLocalId, {
        method: "reqName",
        request: "reqBody",
        response: body
      }).then(() => {
        resolve();
      }).catch(err => {
        return reject(err)
      });
    });

  });
};

node: 6.16.0 npm: 3.10.10 express-http-context: ^1.0.4 express: ^4.14.0

dvneverov commented 5 years ago

The problem usually appeared when there were multiple parallel requests to API. Anyway, finally, updating Node to carbon lts (v8.15.0) solved the issue.

rohitkhatri commented 2 years ago

I have the same issue with node 14, can you please help me with that?