Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect returned class in typescript

When I read following nestjs documentation and tried following code.

https://docs.nestjs.com/exception-filters

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();

    console.log("ctx",ctx);

    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}

console.log("ctx",ctx); returned following

the type os ExecutionContextHost was returned

ctx ExecutionContextHost {
  args: [
    IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      socket: [Socket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      headers: [Object],
      rawHeaders: [Array],
      trailers: {},
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '/event',
      method: 'POST',
      statusCode: null,
      statusMessage: null,
      client: [Socket],
      _consuming: true,
      _dumped: false,
      next: [Function: next],
      baseUrl: '',
      originalUrl: '/event',
      _parsedUrl: [Url],
      params: {},
      query: {},
      res: [ServerResponse],
      body: [Object],
      _body: true,
      length: undefined,
      route: [Route],
      [Symbol(kCapture)]: false,
      [Symbol(RequestTimeout)]: undefined
    },
    ServerResponse {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: false,
      chunkedEncoding: false,
      shouldKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: true,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: false,
      _headerSent: false,
      socket: [Socket],
      _header: null,
      _keepAliveTimeout: 5000,
      _onPendingData: [Function: bound updateOutgoingData],
      _sent100: false,
      _expect_continue: false,
      req: [IncomingMessage],
      locals: [Object: null prototype] {},
      statusCode: 201,
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    [Function: next]
  ],
  constructorRef: null,
  handler: null,
  contextType: 'http',
  getRequest: [Function: getRequest],
  getResponse: [Function: getResponse],
  getNext: [Function: getNext]
}

But when I read ArgumentsHost

https://github.com/nestjs/nest/blob/f472852d/packages/common/interfaces/features/arguments-host.interface.ts#L20

export interface ArgumentsHost {
  getArgs<T extends Array<any> = any[]>(): T;
  getArgByIndex<T = any>(index: number): T;
  switchToRpc(): RpcArgumentsHost;
  switchToHttp(): HttpArgumentsHost;
  switchToWs(): WsArgumentsHost;
}

switchToHttp() method will return HttpArgumentsHost type.

Where ExecutionContextHost come from ?

Why this occured ?

And How can I detect them ?

If someone has opinion, please let me know.

Thanks

like image 225
Heisenberg Avatar asked Mar 22 '26 16:03

Heisenberg


1 Answers

HttpArgumentHost is an interface which ArgumentHost uses to define the methods that switchToHttp() will have like getRequest(), getResponse(), and getNext(). ExecutionContextHost is the implementation of this interface, which is why that's the class that shows up when you log the host.switchToHttp(). As Typescript interfaces do not exist at runtime, you'll never see HttpArgumentHost. If you look at the current implementation you'll see there is a getType() method on ArgumentHost that can return what kind of request you are dealing with, http, rpc, or ws (grapqhl too, but that comes from the @nestjs/graphql package).

like image 105
Jay McDoniel Avatar answered Mar 25 '26 10:03

Jay McDoniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!