index.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import {
  2. Injectable,
  3. NestInterceptor,
  4. ExecutionContext,
  5. CallHandler,
  6. HttpStatus,
  7. BadRequestException,
  8. NotFoundException,
  9. } from '@nestjs/common';
  10. import { map, catchError } from 'rxjs/operators';
  11. import { Observable, throwError } from 'rxjs';
  12. export interface Response<T> {
  13. code: number;
  14. data: T;
  15. }
  16. /**
  17. * transform response to client
  18. */
  19. @Injectable()
  20. export class TransformResInterceptor<T>
  21. implements NestInterceptor<T, Response<T>>
  22. {
  23. intercept(
  24. context: ExecutionContext,
  25. next: CallHandler,
  26. ): Observable<Response<T>> {
  27. return next.handle().pipe(map((data) => ({ code: HttpStatus.OK, data })));
  28. }
  29. }
  30. /**
  31. * Handle error in here.
  32. * Normally depend on status which from milvus service.
  33. */
  34. @Injectable()
  35. export class ErrorInterceptor implements NestInterceptor {
  36. intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
  37. return next.handle().pipe(
  38. catchError((err) => {
  39. console.error(err);
  40. if (err.isAxiosError && err.response) {
  41. const errContent = err.response.data || 'Bad Request';
  42. // from milvus http service
  43. const status = err.response.status || 400;
  44. // operationId is milvus operation id, client need it in response
  45. err.operationId &&
  46. errContent instanceof Object &&
  47. (errContent.operationId = err.operationId);
  48. switch (status) {
  49. case 400:
  50. return throwError(new BadRequestException(errContent));
  51. case 404:
  52. return throwError(new NotFoundException('Not Found Api'));
  53. default:
  54. return throwError(new BadRequestException(errContent));
  55. }
  56. }
  57. return throwError(err);
  58. }),
  59. );
  60. }
  61. }