with-global-providers.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import {
  2. ArgumentMetadata,
  3. ArgumentsHost,
  4. CallHandler,
  5. CanActivate,
  6. Catch,
  7. ExceptionFilter,
  8. ExecutionContext,
  9. HttpException,
  10. Injectable,
  11. NestInterceptor,
  12. PipeTransform,
  13. } from '@nestjs/common';
  14. import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
  15. import { VendurePlugin } from '@vendure/core';
  16. import { Observable } from 'rxjs';
  17. @Injectable()
  18. export class TestInterceptor implements NestInterceptor {
  19. intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
  20. return next.handle();
  21. }
  22. }
  23. @Injectable()
  24. export class TestPipe implements PipeTransform<any> {
  25. async transform(value: any, { metatype }: ArgumentMetadata) {
  26. return value;
  27. }
  28. }
  29. @Injectable()
  30. export class TestGuard implements CanActivate {
  31. canActivate(context: ExecutionContext) {
  32. return true;
  33. }
  34. }
  35. @Catch(HttpException)
  36. export class HttpExceptionFilter implements ExceptionFilter {
  37. catch(exception: HttpException, host: ArgumentsHost) {
  38. const ctx = host.switchToHttp();
  39. const response = ctx.getResponse<any>();
  40. const request = ctx.getRequest<any>();
  41. const status = exception.getStatus();
  42. response.status(status).json({
  43. statusCode: status,
  44. timestamp: new Date().toISOString(),
  45. path: request.url,
  46. });
  47. }
  48. }
  49. /**
  50. * This plugin doesn't do anything other than attempt to register the global Nest providers
  51. * in order to test https://github.com/vendure-ecommerce/vendure/issues/837
  52. */
  53. @VendurePlugin({
  54. providers: [
  55. {
  56. provide: APP_INTERCEPTOR,
  57. useClass: TestInterceptor,
  58. },
  59. {
  60. provide: APP_PIPE,
  61. useClass: TestPipe,
  62. },
  63. {
  64. provide: APP_GUARD,
  65. useClass: TestGuard,
  66. },
  67. {
  68. provide: APP_FILTER,
  69. useClass: HttpExceptionFilter,
  70. },
  71. ],
  72. })
  73. export class PluginWithGlobalProviders {}