|
| 1 | +import { NotFoundException } from "@nestjs/common"; |
| 2 | +import { Observable, throwError } from "rxjs"; |
| 3 | +import { HttpToGrpcInterceptor } from "../../lib"; |
| 4 | +import { RpcException } from "@nestjs/microservices"; |
| 5 | +import { status as GrpcStatusCode } from "@grpc/grpc-js"; |
| 6 | +import { GRPC_CODE_FROM_HTTP } from "../../lib/utils"; |
| 7 | + |
| 8 | +const throwMockException = ( |
| 9 | + Exception: new (...args: any[]) => any, |
| 10 | +): Observable<any> => { |
| 11 | + const exception = new Exception(Exception.name); |
| 12 | + return throwError( |
| 13 | + () => |
| 14 | + new RpcException({ |
| 15 | + message: exception.message, |
| 16 | + code: GRPC_CODE_FROM_HTTP[exception.status], |
| 17 | + }), |
| 18 | + ); |
| 19 | +}; |
| 20 | + |
| 21 | +describe("HttpToGrpcInterceptor", () => { |
| 22 | + let interceptor: HttpToGrpcInterceptor; |
| 23 | + |
| 24 | + beforeAll(() => { |
| 25 | + interceptor = new HttpToGrpcInterceptor(); |
| 26 | + }); |
| 27 | + |
| 28 | + it("Should be defined", () => { |
| 29 | + expect(interceptor).toBeDefined(); |
| 30 | + }); |
| 31 | + |
| 32 | + it("Should convert HTTP exceptions to gRPC exceptions", (done) => { |
| 33 | + const intercept$ = interceptor.intercept({} as any, { |
| 34 | + handle: () => throwMockException(NotFoundException), |
| 35 | + }) as Observable<any>; |
| 36 | + |
| 37 | + intercept$.subscribe({ |
| 38 | + error: (err) => { |
| 39 | + expect(err).toBeInstanceOf(RpcException); |
| 40 | + done(); |
| 41 | + }, |
| 42 | + complete: () => done(), |
| 43 | + }); |
| 44 | + }); |
| 45 | + |
| 46 | + it("Should convert HTTP exceptions to gRPC exceptions", (done) => { |
| 47 | + const intercept$ = interceptor.intercept({} as any, { |
| 48 | + handle: () => throwMockException(NotFoundException), |
| 49 | + }) as Observable<any>; |
| 50 | + |
| 51 | + intercept$.subscribe({ |
| 52 | + error: (err) => { |
| 53 | + expect(err).toBeInstanceOf(RpcException); |
| 54 | + expect(err.error.code).toEqual(GrpcStatusCode.NOT_FOUND); |
| 55 | + done(); |
| 56 | + }, |
| 57 | + complete: () => done(), |
| 58 | + }); |
| 59 | + }); |
| 60 | + |
| 61 | + it("Should contain the HTTP exception error message", (done) => { |
| 62 | + const intercept$ = interceptor.intercept({} as any, { |
| 63 | + handle: () => throwMockException(NotFoundException), |
| 64 | + }) as Observable<any>; |
| 65 | + |
| 66 | + intercept$.subscribe({ |
| 67 | + error: (err) => { |
| 68 | + expect(err).toBeInstanceOf(RpcException); |
| 69 | + expect(err.message).toEqual(NotFoundException.name); |
| 70 | + done(); |
| 71 | + }, |
| 72 | + complete: () => done(), |
| 73 | + }); |
| 74 | + }); |
| 75 | +}); |
0 commit comments