djfdyuruiry / ts-lambda-api

Build REST API's using Typescript & AWS Lambda
MIT License
54 stars 15 forks source link

Question: Local storage (cls-hooked) setup to log request/response data #56

Closed hemanth1226 closed 3 years ago

hemanth1226 commented 3 years ago

I am trying to use "https://www.npmjs.com/package/cls-hooked" in my project to store request and response data and log them. But i am facing issues integrating it. Do you have any option to store the data and retrieve them in controllers or services and log the data?

This is what i am doing:

import * as cls from "cls-hooked";
const clsNamespace = cls.createNamespace("app");
app.configureApi((api) => {
  api.use((req: Request, res: Response, next: () => void) => {
    clsNamespace.bind(req as any);
    clsNamespace.run(() => {
      clsNamespace.set("url", url);
      next();
    });
});

When i am trying to access the stored data in a component, i am getting the value as undefined.

import * as cls from "cls-hooked";
private clsNamespace = cls.getNamespace("app");
console.log(clsNamespace.get('url')) // prints undefined
djfdyuruiry commented 3 years ago

Hello

I am not familiar with this framework - but where/when is the second block of code being executed. Is it in an endpoint?

hemanth1226 commented 3 years ago

Hi, thank you for your time. Yes it is inside an endpoint.

I am using this framework for Continuation Local Storage. I have tried using async-hooks as well but that didn't work either.

I have attached a sample zip file where i added console logs. I hope this helps understanding the issue. Please let me know if this doesn't help.

test-lambda-api.zip

Thanks!

Muthuveerappanv commented 3 years ago

@hemanth1226 @djfdyuruiry was able to resolve this using a runPromise option within the cls-hooked library

app.configureApi((api) => {
  api.use((req: Request, res: Response, next: () => void) => {
    clsNamespace.bind(req as any);
    clsNamespace.bind(res as any);

    clsNamespace.runPromise(() => {
      clsNamespace.set("x-amzn-trace-id", "test id");
      // console.log(clsNamespace, "inside run");
      return Promise.resolve(next());
    });
  });
});