diff --git a/package.json b/package.json index 64591a7..72f6231 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,8 @@ "@types/jest": "^25.1.4", "@types/node": "^13.9.0", "@types/supertest": "^2.0.7", + "class-transformer": "^0.3.2", + "class-validator": "^0.13.1", "jest": "^25.1.0", "prettier": "^1.15.3", "rxjs": "^6.0.0", diff --git a/src/index.spec.ts b/src/index.spec.ts index e91f735..95d8481 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -45,6 +45,10 @@ describe("json-rpc-e2e", () => { expect(res).toStrictEqual({ test: "hi" }); }); + it(`should throw if sends an invalid DTO`, async () => { + let res = service.invokeClientService({ test: "" }); + await expect(res).rejects.toThrow("hi"); + }); it(`should fail to make a request with an unauthorized JsonRpcClient`, async () => { let result = unauthorizedService.invokeClientService({ test: "hi" }); await expect(result).rejects.toThrowError("Forbidden resource"); diff --git a/src/test-handler.ts b/src/test-handler.ts index f4dc446..06be732 100644 --- a/src/test-handler.ts +++ b/src/test-handler.ts @@ -10,10 +10,12 @@ import { UseInterceptors, UseGuards, Scope, - Inject + ValidationPipe } from "@nestjs/common"; import { Ctx } from "@nestjs/microservices"; +import { IsNotEmpty } from "class-validator"; + import { CodedRpcException, JsonRpcContext, RpcController, RpcMethod, RpcService } from "."; const initialModuleState = { @@ -83,6 +85,11 @@ class TestGuard implements CanActivate { type IRpcTestService = RpcController; +export class TestDto { + @IsNotEmpty() + test!: string; +} + @RpcService({ namespace: "test" }) @@ -92,14 +99,6 @@ export class TestService implements IRpcTestService { DecorationsState.serviceConstructorCount = DecorationsState.serviceConstructorCount + 1; } - @UsePipes(TestPipe) - @UseInterceptors(TestInterceptor) - @UseGuards(TestGuard) - @RpcMethod() - public async invoke(params: { test: string }) { - return Promise.resolve(params); - } - @UsePipes(TestPipe) @UseInterceptors(TestInterceptor) @UseGuards(TestGuard) @@ -110,10 +109,11 @@ export class TestService implements IRpcTestService { } @UsePipes(TestPipe) + @UsePipes(ValidationPipe) @UseInterceptors(TestInterceptor) @UseGuards(TestGuard) @RpcMethod() - public async invokeClientService(params: { test: string }) { + public async invokeClientService(params: TestDto) { return Promise.resolve(params); } @@ -131,7 +131,6 @@ export class TestService implements IRpcTestService { } export interface ITestClientService { - invoke(params: { test: string }): Promise<{ test: string }>; invokeClientService(params: { test: string }): Promise<{ test: string }>; testError(params: { errorTest: string }): Promise; injectContext(params: {}): Promise<{ key: string | undefined }>;