AsyncLocalStorage loose context in mongoose hooks POST save

358 Views Asked by At

How to do to maintain the same context in all flow ?

Why the AsyncHooks context is loose inside the Schema.post('save') but not in Schema.pre('save')?

Please, look the testes-mongoose branch and execute yarn example:mongoose. GIT HUB Source: https://github.com/almerindo/traceability/tree/testes-mongoose

File: examples/mongoose/schema/traceability.schema.ts

TraceabilitySchema.pre('save', function(next) {
  const context = ContextAsyncHooks.getContext();
  console.info({context})
  Logger.info('Has This log a trackId in PRE SAVE? ');
  next();
});

TraceabilitySchema.post('save', function(doc) {
  const context = ContextAsyncHooks.getContext();
  console.info({context})
  Logger.info('Has This log a trackId in POST SAVE? ');
});

The Output is:

{"message":"BEGIN OF ALL","level":"info","trackId":"952ac121-5a8c-46b5-a054-52b8185c7023","timestamp":"2021-04-27T11:54:39.756Z"}
{ context: { trackId: '952ac121-5a8c-46b5-a054-52b8185c7023' } }
{"message":"Has This log a trackId in PRE SAVE? ","level":"info","trackId":"952ac121-5a8c-46b5-a054-52b8185c7023","timestamp":"2021-04-27T11:54:39.764Z"}
Conexão estabelecida -Mongo {"useNewUrlParser":true,"authSource":"admin","useUnifiedTopology":true}
{ context: undefined }
{"message":"Has This log a trackId in POST SAVE? ","level":"info","timestamp":"2021-04-27T11:54:39.794Z"}
{"message":"END OF ALL","level":"info","trackId":"952ac121-5a8c-46b5-a054-52b8185c7023","timestamp":"2021-04-27T11:54:39.795Z"}

Note: Only the output inside MONGOOSE HOOKS POST SAVE the context is NULL

0

There are 0 best solutions below