1

如何在所有流程中保持相同的上下文?

为什么 AsyncHooks 上下文在 Schema.post('save') 中是松散的,但在 Schema.pre('save') 中却没有?

请查看 testes-mongoose 分支并执行yarn example:mongoose。GIT HUB 来源: https ://github.com/almerindo/traceability/tree/testes-mongoose

文件: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? ');
});

输出是:

{"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"}

注意:只有 MONGOOSE HOOKS POST SAVE 上下文中的输出为 NULL

4

0 回答 0