@nestjs/common/interfaces#HttpArgumentsHost TypeScript Examples

The following examples show how to use @nestjs/common/interfaces#HttpArgumentsHost. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: all-exceptions.filter.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
catch(exception: any, host: ArgumentsHost) {
    const ctx: HttpArgumentsHost = host.switchToHttp();
    const res = ctx.getResponse<ExpressResponse>();
    const exceptionResponse: null | ExceptionResponse = exception.getResponse
      ? (exception.getResponse() as ExceptionResponse)
      : null;
    const status: number = exception.getStatus ? exception.getStatus() : 500;

    const mongodbCodes = {
      bulkWriteError: 11000, // a duplicate error code in mongoose
    };

    if (exception.code === mongodbCodes.bulkWriteError) {
      return res.status(HttpStatus.CONFLICT).json(
        new Error({
          source: { pointer: '/data/attributes/email' },
          title: 'Duplicate key',
          detail: exception.message,
        }),
      );
    }

    if (exception.response?.errorType === 'ValidationError') {
      return res.status(HttpStatus.BAD_REQUEST).json(
        new Error(exceptionResponse ? exceptionResponse.errors : {}),
      );
    }

    return res.status(status).json(new Error({
      title: exceptionResponse?.error,
      detail: exception?.message,
    }));
  }
Example #2
Source File: all-exception.filter.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
catch(exception: any, host: ArgumentsHost) {
    const ctx: HttpArgumentsHost = host.switchToHttp();
    const res = ctx.getResponse<ExpressResponse>();
    const exceptionResponse: null | ExceptionResponse = exception.getResponse
      ? (exception.getResponse() as ExceptionResponse)
      : null;
    const status: number = exception.getStatus ? exception.getStatus() : 500;

    const mongodbCodes = {
      bulkWriteError: 11000, // a duplicate error code in mongoose
    };

    if (exception.code === mongodbCodes.bulkWriteError) {
      return res.status(HttpStatus.CONFLICT).json({
        message: exceptionResponse?.message,
        error: exceptionResponse?.error,
      });
    }

    return res.status(status).json({
      message: exceptionResponse?.message,
      error: exceptionResponse?.error,
    });
  }
Example #3
Source File: all-exceptions.filter.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
catch(exception: any, host: ArgumentsHost) {
    const ctx: HttpArgumentsHost = host.switchToHttp();
    const res = ctx.getResponse<ExpressResponse>();
    const exceptionMessage: string | null = exception.message || null;
    const exceptionResponse: null | ExceptionResponse = exception.getResponse
      ? (exception.getResponse() as ExceptionResponse)
      : null;
    const status: number = exception.getStatus ? exception.getStatus() : 500;

    const mysqlCodes = {
      duplicateError: 'ER_DUP_ENTRY',
    };

    if (exception.code === mysqlCodes.duplicateError) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: exceptionMessage, error: exceptionResponse });
    }

    return res.status(status).json({
      message: exceptionMessage,
      error: exceptionResponse,
    });
  }
Example #4
Source File: create-execution-context.ts    From google-recaptcha with MIT License 6 votes vote down vote up
function createArgumentHost(req: Partial<Request>): HttpArgumentsHost {
    return new class implements HttpArgumentsHost {
        getRequest<T = any>(): T {
            return req as T;
        }

        getNext<T = any>(): T {
            console.error('Method \'getNext\' doesn\'t implemented');
            return undefined;
        }


        getResponse<T = any>(): T {
            console.error('Method \'getResponse\' doesn\'t implemented');
            return undefined;
        }
    }
}
Example #5
Source File: decorator.spec.ts    From nestjs-paginate with MIT License 6 votes vote down vote up
function expressContextFactory(query: ExpressRequest['query']): Partial<ExecutionContext> {
    const mockContext: Partial<ExecutionContext> = {
        switchToHttp: (): HttpArgumentsHost =>
            Object({
                getRequest: (): Partial<ExpressRequest> =>
                    Object({
                        protocol: 'http',
                        get: () => 'localhost',
                        originalUrl: '/items?search=2423',
                        query: query,
                    }),
            }),
    }
    return mockContext
}
Example #6
Source File: decorator.spec.ts    From nestjs-paginate with MIT License 6 votes vote down vote up
function fastifyContextFactory(query: FastifyRequest['query']): Partial<ExecutionContext> {
    const mockContext: Partial<ExecutionContext> = {
        switchToHttp: (): HttpArgumentsHost =>
            Object({
                getRequest: (): Partial<FastifyRequest> =>
                    Object({
                        protocol: 'http',
                        hostname: 'localhost',
                        url: '/items?search=2423',
                        query: query,
                    }),
            }),
    }
    return mockContext
}
Example #7
Source File: create-execution-context.ts    From google-recaptcha with MIT License 5 votes vote down vote up
export function createExecutionContext(handler: Function, req: Partial<Request>): ExecutionContext {
    return new class implements ExecutionContext {
        getHandler(): Function {
            return handler;
        }

        switchToHttp(): HttpArgumentsHost {
            return createArgumentHost(req);
        }

        getArgByIndex<T = any>(index: number): T {
            console.error('Method \'getArgByIndex\' doesn\'t implemented');
            return undefined;
        }

        getArgs<T = any[]>(): T {
            console.error('Method \'getArgs\' doesn\'t implemented');
            return undefined;
        }

        getClass<T = any>(): Type<T> {
            console.error('Method \'getClass\' doesn\'t implemented');
            return undefined;
        }

        getType<TContext = ContextType>(): TContext {
            return 'http' as any;
        }

        switchToRpc(): RpcArgumentsHost {
            console.error('Method \'switchToRpc\' doesn\'t implemented');
            return undefined;
        }

        switchToWs(): WsArgumentsHost {
            console.error('Method \'switchToWs\' doesn\'t implemented');
            return undefined;
        }
    }
}
Example #8
Source File: roles.guard.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('RolesGuard', () => {
  let guard: RolesGuard;
  let reflector: Reflector;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        RolesGuard,
        {
          provide: Reflector,
          useValue: {
            constructor: jest.fn(),
            get: jest.fn(),
          },
        },
      ],
    }).compile();

    guard = module.get<RolesGuard>(RolesGuard);
    reflector = module.get<Reflector>(Reflector);
  });

  afterEach(async () => {
    jest.clearAllMocks();
  });

  it('should be defined', () => {
    expect(guard).toBeDefined();
  });

  it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
    jest.spyOn(reflector, 'get').mockImplementation((a: any, b: any) => []);
    const context = createMock<ExecutionContext>();
    const result = await guard.canActivate(context);

    expect(result).toBeTruthy();
    expect(reflector.get).toBeCalled();
  });

  it('should return true if the `HasRoles` decorator is set', async () => {
    jest
      .spyOn(reflector, 'get')
      .mockImplementation((a: any, b: any) => [RoleType.USER]);
    const context = createMock<ExecutionContext>({
      getHandler: jest.fn(),
      switchToHttp: jest.fn().mockReturnValue({
        getRequest: jest.fn().mockReturnValue({
          user: { roles: [RoleType.USER] },
        } as AuthenticatedRequest),
      }),
    });

    const result = await guard.canActivate(context);
    expect(result).toBeTruthy();
    expect(reflector.get).toBeCalled();
  });

  it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
    jest.spyOn(reflector, 'get').mockReturnValue([RoleType.ADMIN]);
    const request = {
      user: { roles: [RoleType.USER] },
    } as AuthenticatedRequest;
    const context = createMock<ExecutionContext>();
    const httpArgsHost = createMock<HttpArgumentsHost>({
      getRequest: () => request,
    });
    context.switchToHttp.mockImplementation(() => httpArgsHost);

    const result = await guard.canActivate(context);
    expect(result).toBeFalsy();
    expect(reflector.get).toBeCalled();
  });
});
Example #9
Source File: roles.guard.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('RolesGuard(ts-mockito)', () => {
  let guard: RolesGuard;
  const reflecter = mock(Reflector);
  beforeEach(() => {
    guard = new RolesGuard(instance(reflecter));
  });

  afterEach(() => {
    reset();
  });

  it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
    const context = mock<ExecutionContext>();
    when(context.getHandler()).thenReturn({} as any);

    const contextInstacne = instance(context);
    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([] as RoleType[]);
    const result = await guard.canActivate(contextInstacne);

    expect(result).toBeTruthy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });

  it('should return true if the `HasRoles` decorator is set', async () => {
    const context = mock<ExecutionContext>();

    when(context.getHandler()).thenReturn({} as any);

    const arguHost = mock<HttpArgumentsHost>();
    when(arguHost.getRequest()).thenReturn({
      user: { roles: [RoleType.USER] },
    } as any);

    when(context.switchToHttp()).thenReturn(instance(arguHost));
    const contextInstacne = instance(context);

    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([RoleType.USER] as RoleType[]);

    const result = await guard.canActivate(contextInstacne);
    console.log(result);
    expect(result).toBeTruthy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });

  it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
    const context = mock<ExecutionContext>();

    when(context.getHandler()).thenReturn({} as any);

    // logged in as USER
    const arguHost = mock<HttpArgumentsHost>();
    when(arguHost.getRequest()).thenReturn({
      user: { roles: [RoleType.USER] },
    } as any);

    when(context.switchToHttp()).thenReturn(instance(arguHost));
    const contextInstacne = instance(context);

    // but requires ADMIN
    when(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).thenReturn([RoleType.ADMIN] as RoleType[]);

    const result = await guard.canActivate(contextInstacne);
    console.log(result);
    expect(result).toBeFalsy();
    verify(
      reflecter.get<RoleType[]>(HAS_ROLES_KEY, contextInstacne.getHandler()),
    ).once();
  });
});
Example #10
Source File: roles.guard.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('RoelsGuard(jest-mock-extended)', () => {
  let guard: RolesGuard;
  const reflecter = jestMock<Reflector>();

  beforeEach(() => {
    guard = new RolesGuard(reflecter);
  });

  afterEach(() => {
    mockClear(reflecter);
  });

  it('should be defined', () => {
    expect(guard).toBeDefined();
  });

  it('should skip(return true) if the `HasRoles` decorator is not set', async () => {
    const context = jestMock<ExecutionContext>();
    context.getHandler.mockReturnValue({} as any);
    reflecter.get
      .mockReturnValue([])
      .calledWith(HAS_ROLES_KEY, context.getHandler());

    const result = await guard.canActivate(context);

    expect(result).toBeTruthy();
    expect(reflecter.get).toBeCalledTimes(1);
  });

  it('should return true if the `HasRoles` decorator is set', async () => {
    const context = jestMock<ExecutionContext>();
    context.getHandler.mockReturnValue({} as any);

    const arguHost = jestMock<HttpArgumentsHost>();
    arguHost.getRequest.mockReturnValue({
      user: { roles: [RoleType.USER] },
    } as any);

    context.switchToHttp.mockReturnValue(arguHost);

    reflecter.get
      .mockReturnValue([RoleType.USER])
      .calledWith(HAS_ROLES_KEY, context.getHandler());

    const result = await guard.canActivate(context);

    expect(result).toBeTruthy();
    expect(reflecter.get).toBeCalledTimes(1);
  });

  it('should return false if the `HasRoles` decorator is set but role is not allowed', async () => {
    // logged in as USER
    const context = jestMock<ExecutionContext>();
    context.getHandler.mockReturnValue({} as any);

    const arguHost = jestMock<HttpArgumentsHost>();
    arguHost.getRequest.mockReturnValue({
      user: { roles: [RoleType.USER] },
    } as any);

    context.switchToHttp.mockReturnValue(arguHost);

    //but requires ADMIN
    reflecter.get
      .mockReturnValue([RoleType.ADMIN])
      .calledWith(HAS_ROLES_KEY, context.getHandler());

    const result = await guard.canActivate(context);

    expect(result).toBeFalsy();
    expect(reflecter.get).toBeCalledTimes(1);
  });
});