#Response Custom

17 messages · Page 1 of 1 (latest)

urban estuary
#

So I'm getting an error like this

[Nest] 542997  - 05/03/2023, 10:24:09 PM   ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'message')
TypeError: Cannot read properties of undefined (reading 'message')
    at chatbot-backend/src/common/interceptor/response.interceptor.ts:38:22
    at chatbot-backend/node_modules/rxjs/src/internal/operators/map.ts:58:33
    at OperatorSubscriber._this._next (chatbot-backend/node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts:70:13)

With the code in response.interceptor.ts like this

...

export interface Response<T> {
  status: string;
  statusCode: number;
  author: string;
  apiVersion: number;
  message: string;
  data: T;
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    const request = context.switchToHttp().getRequest();
    const version = +request.url.match(/\/v[0-9]/)?.[0].slice(2);
    const response = context.switchToHttp().getResponse();

    return next.handle().pipe(
      map((res) => ({
        status: [200, 201, 204].includes(response.statusCode)
          ? 'success'
          : 'error',
        statusCode: response.statusCode,
        author: APP_AUTHOR,
        apiVersion: isNaN(version) ? null : version,
        message: res.message ?? null,
        data: res.data ?? null,
      })),
    );
  }
}

This is all in a normal controller but when you get a controller like this

async create(
    @Res({ passthrough: true }) res: Response,
) {}

an error will occur, I am forced to do this because I use the baileys library in NestJS.
Can anyone help with the problem where the service will throw a response to the controller?

thick bridge
#

You don't return anything from that endpoint, so the interceptor can't read the message or data properties

#

It's not that .message is incredible and therefore triggers the ?? it's that res is undefined in the interceptor and you have a runtime error. You'd need res?.message ?? null to get around it

urban estuary
#

So I have a create method and then it's linked to this method, meaning that the response in this method doesn't return a value?

private async handleNormalConnectionUpdate(
    connectionState: Partial<ConnectionState>,
    sessionId: string,
    res: Response,
  ) {
    if (connectionState.qr?.length) {
      if (res && !res.headersSent) {
        try {
          const qr = await toDataURL(connectionState.qr);
          res.status(200).json({
            message: 'Created session successfully',
            data: qr,
          });
          return;
        } catch (e) {
          logger.error(e, 'An error occured during QR generation');
          res.status(500).json({ message: 'Unable to generate QR' });
        }
      }
      this.destroy(sessionId);
    }
  }
thick bridge
#

This method doesn't return anything, but it does send a response. However, the interceptor will still fire

urban estuary
thick bridge
#

Whatever you return from the service method is what the controller will get. Whatever the controller returns is what nest will usually send (sheet the interceptor)

urban estuary
thick bridge
#

What is Baileys?

urban estuary
thick bridge
#

I don't see why you wouldn't be able to use it. Anything that is valid in node can usually be done in Nest

urban estuary
thick bridge
#

I don't see what that script had to do with HTTP at all. It's not tied to a specific route. In theory, you could take that same script, add it before you can app.lisyen() like they do in the index, and it should work just fine

urban estuary
thick bridge
#

What do you mean? What problem?

urban estuary
thick bridge
#

How? Where? What are you doing?