From f89f7cfcd20b772600a0c98995bf1582e1b6e9de Mon Sep 17 00:00:00 2001 From: Alex H Date: Mon, 11 Mar 2024 17:59:11 +0100 Subject: [PATCH] feat(nestjs-json-rpc): default transport for rpc - http transport - validation - explorer need service Closes: #77 --- .verdaccio/config.yml | 28 -- apps/json-api-server/src/app/app.module.ts | 2 + .../json-api-server/src/app/rpc/rpc.module.ts | 13 + libs/json-rpc/nestjs-json-rpc/.eslintrc.json | 25 ++ libs/json-rpc/nestjs-json-rpc/README.md | 11 + libs/json-rpc/nestjs-json-rpc/jest.config.ts | 11 + libs/json-rpc/nestjs-json-rpc/package.json | 10 + libs/json-rpc/nestjs-json-rpc/project.json | 24 ++ libs/json-rpc/nestjs-json-rpc/src/index.ts | 7 + .../src/lib/constants/index.ts | 18 + .../src/lib/decorators/index.ts | 45 +++ .../controllers/json-rpc.controller.ts | 19 + .../filter/rpc-error-exception.filter.ts | 23 ++ .../http-transport/http-transport.module.ts | 22 ++ .../nestjs-json-rpc/src/lib/modules/index.ts | 2 + .../modules/util/pipe/input-data.pipe.spec.ts | 144 +++++++ .../lib/modules/util/pipe/input-data.pipe.ts | 51 +++ .../util/service/explorer.service.spec.ts | 26 ++ .../modules/util/service/explorer.service.ts | 33 ++ .../util/service/handler.service.spec.ts | 358 ++++++++++++++++++ .../modules/util/service/handler.service.ts | 243 ++++++++++++ .../src/lib/modules/util/service/index.ts | 2 + .../src/lib/modules/util/util.module.spec.ts | 33 ++ .../src/lib/modules/util/util.module.ts | 35 ++ .../src/lib/nestjs-json-rpc.module.ts | 37 ++ .../lib/providers/async-iterator.provider.ts | 84 ++++ .../src/lib/providers/index.ts | 2 + .../providers/map-handler-store.provider.ts | 7 + .../lib/providers/zod-input-data.provider.ts | 8 + .../src/lib/types/error-code-type.ts | 8 + .../src/lib/types/error-payloade.ts | 23 ++ .../nestjs-json-rpc/src/lib/types/index.ts | 5 + .../src/lib/types/module-options.ts | 25 ++ .../nestjs-json-rpc/src/lib/types/payloade.ts | 68 ++++ .../nestjs-json-rpc/src/lib/types/utils.ts | 1 + .../nestjs-json-rpc/src/lib/utils/error.ts | 45 +++ .../nestjs-json-rpc/src/lib/utils/index.ts | 1 + libs/json-rpc/nestjs-json-rpc/tsconfig.json | 22 ++ .../nestjs-json-rpc/tsconfig.lib.json | 16 + .../nestjs-json-rpc/tsconfig.spec.json | 14 + tsconfig.base.json | 3 + 41 files changed, 1526 insertions(+), 28 deletions(-) delete mode 100644 .verdaccio/config.yml create mode 100644 apps/json-api-server/src/app/rpc/rpc.module.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/.eslintrc.json create mode 100644 libs/json-rpc/nestjs-json-rpc/README.md create mode 100644 libs/json-rpc/nestjs-json-rpc/jest.config.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/package.json create mode 100644 libs/json-rpc/nestjs-json-rpc/project.json create mode 100644 libs/json-rpc/nestjs-json-rpc/src/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/constants/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/decorators/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/controllers/json-rpc.controller.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/filter/rpc-error-exception.filter.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/http-transport.module.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.spec.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.spec.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.spec.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.spec.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/nestjs-json-rpc.module.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/providers/async-iterator.provider.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/providers/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/providers/map-handler-store.provider.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/providers/zod-input-data.provider.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/types/error-code-type.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/types/error-payloade.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/types/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/types/module-options.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/types/payloade.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/types/utils.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/utils/error.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/src/lib/utils/index.ts create mode 100644 libs/json-rpc/nestjs-json-rpc/tsconfig.json create mode 100644 libs/json-rpc/nestjs-json-rpc/tsconfig.lib.json create mode 100644 libs/json-rpc/nestjs-json-rpc/tsconfig.spec.json diff --git a/.verdaccio/config.yml b/.verdaccio/config.yml deleted file mode 100644 index a007fe8..0000000 --- a/.verdaccio/config.yml +++ /dev/null @@ -1,28 +0,0 @@ -# path to a directory with all packages -storage: ../tmp/local-registry/storage - -# a list of other known repositories we can talk to -uplinks: - npmjs: - url: https://registry.npmjs.org/ - maxage: 60m - -packages: - '**': - # give all users (including non-authenticated users) full access - # because it is a local registry - access: $all - publish: $all - unpublish: $all - - # if package is not available locally, proxy requests to npm registry - proxy: npmjs - -# log settings -logs: - type: stdout - format: pretty - level: warn - -publish: - allow_offline: true # set offline to true to allow publish offline diff --git a/apps/json-api-server/src/app/app.module.ts b/apps/json-api-server/src/app/app.module.ts index 3d7ea99..4540324 100644 --- a/apps/json-api-server/src/app/app.module.ts +++ b/apps/json-api-server/src/app/app.module.ts @@ -3,12 +3,14 @@ import { LoggerModule } from 'nestjs-pino'; import { DatabaseModule } from 'database'; import { ResourcesModule } from './resources/resources.module'; +import { RpcModule } from './rpc/rpc.module'; import * as process from 'process'; @Module({ imports: [ DatabaseModule, ResourcesModule, + RpcModule, LoggerModule.forRoot({ pinoHttp: { level: process.env['NODE_ENV'] === 'test' ? 'silent' : 'debug', diff --git a/apps/json-api-server/src/app/rpc/rpc.module.ts b/apps/json-api-server/src/app/rpc/rpc.module.ts new file mode 100644 index 0000000..7420b11 --- /dev/null +++ b/apps/json-api-server/src/app/rpc/rpc.module.ts @@ -0,0 +1,13 @@ +import { Module } from '@nestjs/common'; +import { NestjsJsonRpcModule, TransportType } from '@klerick/nestjs-json-rpc'; + +@Module({ + imports: [ + NestjsJsonRpcModule.forRootAsync({ + path: 'rpc', + transport: TransportType.HTTP, + }), + ], + // providers: [ContestRpc, ParseIntArrayPipe, LineUpSchemaPipe], +}) +export class RpcModule {} diff --git a/libs/json-rpc/nestjs-json-rpc/.eslintrc.json b/libs/json-rpc/nestjs-json-rpc/.eslintrc.json new file mode 100644 index 0000000..c9748d2 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/.eslintrc.json @@ -0,0 +1,25 @@ +{ + "extends": ["../../../.eslintrc.base.json"], + "ignorePatterns": ["!**/*"], + "overrides": [ + { + "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], + "rules": {} + }, + { + "files": ["*.ts", "*.tsx"], + "rules": {} + }, + { + "files": ["*.js", "*.jsx"], + "rules": {} + }, + { + "files": ["*.json"], + "parser": "jsonc-eslint-parser", + "rules": { + "@nx/dependency-checks": "error" + } + } + ] +} diff --git a/libs/json-rpc/nestjs-json-rpc/README.md b/libs/json-rpc/nestjs-json-rpc/README.md new file mode 100644 index 0000000..7fdb71b --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/README.md @@ -0,0 +1,11 @@ +# nestjs-json-rpc + +This library was generated with [Nx](https://nx.dev). + +## Building + +Run `nx build nestjs-json-rpc` to build the library. + +## Running unit tests + +Run `nx test nestjs-json-rpc` to execute the unit tests via [Jest](https://jestjs.io). diff --git a/libs/json-rpc/nestjs-json-rpc/jest.config.ts b/libs/json-rpc/nestjs-json-rpc/jest.config.ts new file mode 100644 index 0000000..f77fba8 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/jest.config.ts @@ -0,0 +1,11 @@ +/* eslint-disable */ +export default { + displayName: 'nestjs-json-rpc', + preset: '../../../jest.preset.js', + testEnvironment: 'node', + transform: { + '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '/tsconfig.spec.json' }], + }, + moduleFileExtensions: ['ts', 'js', 'html'], + coverageDirectory: '../../../coverage/libs/json-rpc/nestjs-json-rpc', +}; diff --git a/libs/json-rpc/nestjs-json-rpc/package.json b/libs/json-rpc/nestjs-json-rpc/package.json new file mode 100644 index 0000000..44d0fa3 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/package.json @@ -0,0 +1,10 @@ +{ + "name": "@klerick/nestjs-json-rpc", + "version": "0.0.1", + "dependencies": { + "tslib": "^2.3.0" + }, + "type": "commonjs", + "main": "./src/index.js", + "typings": "./src/index.d.ts" +} diff --git a/libs/json-rpc/nestjs-json-rpc/project.json b/libs/json-rpc/nestjs-json-rpc/project.json new file mode 100644 index 0000000..219a861 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/project.json @@ -0,0 +1,24 @@ +{ + "name": "nestjs-json-rpc", + "$schema": "../../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "libs/json-rpc/nestjs-json-rpc/src", + "projectType": "library", + "targets": { + "build": { + "executor": "@nx/js:tsc", + "outputs": ["{options.outputPath}"], + "options": { + "outputPath": "dist/libs/json-rpc/nestjs-json-rpc", + "tsConfig": "libs/json-rpc/nestjs-json-rpc/tsconfig.lib.json", + "packageJson": "libs/json-rpc/nestjs-json-rpc/package.json", + "main": "libs/json-rpc/nestjs-json-rpc/src/index.ts", + "assets": ["libs/json-rpc/nestjs-json-rpc/*.md"] + } + }, + "publish": { + "command": "node tools/scripts/publish.mjs nestjs-json-rpc {args.ver} {args.tag}", + "dependsOn": ["build"] + } + }, + "tags": [] +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/index.ts b/libs/json-rpc/nestjs-json-rpc/src/index.ts new file mode 100644 index 0000000..0674303 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/index.ts @@ -0,0 +1,7 @@ +export * from './lib/nestjs-json-rpc.module'; +export { TransportType, CommonRpcConfig, ErrorCodeType } from './lib/types'; +export { + fromRpcErrorToRpcErrorObject, + createError, + RpcError, +} from './lib/utils'; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/constants/index.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/constants/index.ts new file mode 100644 index 0000000..47dfe49 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/constants/index.ts @@ -0,0 +1,18 @@ +import { ErrorCodeType } from '../types'; + +export const JsonRpcMetadataKey = '__rpc-metadata__'; +export const JsonRpcMetadataKeyParamPipe = '__rpc-metadata-param-pipe__'; + +export const MAP_HANDLER = Symbol('MAP_HANDLER'); +export const RPC_CONTEXT = Symbol('RPC_CONTEXT'); +export const ASYNC_ITERATOR_FACTORY = Symbol('ASYNC_ITERATOR_FACTORY'); +export const ZOD_INPUT_DATA = Symbol('ZOD_INPUT_DATA'); + +export const ErrorCode: Record = { + [ErrorCodeType.ParseError]: -32700, + [ErrorCodeType.InvalidRequest]: -32600, + [ErrorCodeType.MethodNotFound]: -32601, + [ErrorCodeType.InvalidParams]: -32602, + [ErrorCodeType.InternalError]: -32603, + [ErrorCodeType.ServerError]: -32000, +} as const; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/decorators/index.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/decorators/index.ts new file mode 100644 index 0000000..42af904 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/decorators/index.ts @@ -0,0 +1,45 @@ +import { + applyDecorators, + Inject, + Injectable, + PipeTransform, + SetMetadata, +} from '@nestjs/common'; +import { Type } from '@nestjs/common/interfaces'; +import { + JsonRpcMetadataKey, + JsonRpcMetadataKeyParamPipe, + RPC_CONTEXT, +} from '../constants'; + +export const RpcHandler = () => { + return applyDecorators(SetMetadata(JsonRpcMetadataKey, true), Injectable()); +}; + +// export function InjectContext(): PropertyDecorator { +// return (target, key) => { +// Inject(RPC_CONTEXT)(target, key); +// }; +// } + +export const RpcParamsPipe = ( + pipe: Type | PipeTransform +): ParameterDecorator => { + return (target, key, index) => { + if (!key) { + throw Error('key is undefined'); + } + const args: Record | PipeTransform> = + Reflect.getMetadata( + JsonRpcMetadataKeyParamPipe, + target.constructor, + key + ) || {}; + Reflect.defineMetadata( + JsonRpcMetadataKeyParamPipe, + Object.assign(Object.assign({}, args), { [`params:${index}`]: pipe }), + target.constructor, + key + ); + }; +}; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/controllers/json-rpc.controller.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/controllers/json-rpc.controller.ts new file mode 100644 index 0000000..b9cb28c --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/controllers/json-rpc.controller.ts @@ -0,0 +1,19 @@ +import { Body, Controller, Inject, Post, UseFilters } from '@nestjs/common'; +import { HandlerService } from '../../util/service'; +import { InputDataPipe } from '../../util/pipe/input-data.pipe'; +import { PayloadRpcData, RpcResult } from '../../../types'; +import { RpcErrorObject } from '../../../types/error-payloade'; +import { RpcErrorExceptionFilter } from '../filter/rpc-error-exception.filter'; + +@Controller('/') +export class JsonRpcController { + @Inject(HandlerService) private readonly handlerService!: HandlerService; + + @Post('') + @UseFilters(new RpcErrorExceptionFilter()) + async handler( + @Body(InputDataPipe) body: PayloadRpcData + ): Promise> { + return this.handlerService.runRpc(body); + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/filter/rpc-error-exception.filter.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/filter/rpc-error-exception.filter.ts new file mode 100644 index 0000000..16b204f --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/filter/rpc-error-exception.filter.ts @@ -0,0 +1,23 @@ +import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common'; + +import { + RpcError, + fromRpcErrorToRpcErrorObject, + createError, +} from '../../../utils'; +import { RpcErrorObject, ErrorCodeType } from '../../../types'; + +@Catch() +export class RpcErrorExceptionFilter implements ExceptionFilter { + catch(exception: Error, host: ArgumentsHost): void { + let body: RpcErrorObject; + if (exception instanceof RpcError) { + body = fromRpcErrorToRpcErrorObject(exception); + } else { + body = fromRpcErrorToRpcErrorObject( + createError(ErrorCodeType.ServerError, exception.message) + ); + } + host.switchToHttp().getResponse().send(body); + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/http-transport.module.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/http-transport.module.ts new file mode 100644 index 0000000..b218fe4 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/http-transport/http-transport.module.ts @@ -0,0 +1,22 @@ +import { DynamicModule, Provider } from '@nestjs/common'; +import { Type } from '@nestjs/common/interfaces/type.interface'; +import { ForwardReference } from '@nestjs/common/interfaces/modules/forward-reference.interface'; + +import { JsonRpcController } from './controllers/json-rpc.controller'; + +export class HttpTransportModule { + static forRoot( + providers: Provider[], + imports: Array< + Type | DynamicModule | Promise | ForwardReference + > = [] + ): DynamicModule { + return { + module: HttpTransportModule, + providers, + controllers: [JsonRpcController], + // exports: [RPC_CONTEXT], + imports, + }; + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/index.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/index.ts new file mode 100644 index 0000000..e720cd3 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/index.ts @@ -0,0 +1,2 @@ +export * from './http-transport/http-transport.module'; +export * from './util/util.module'; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.spec.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.spec.ts new file mode 100644 index 0000000..5bab2d2 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.spec.ts @@ -0,0 +1,144 @@ +import { Test } from '@nestjs/testing'; +import { InputDataPipe } from './input-data.pipe'; +import { ErrorCodeType, PayloadRpcData } from '../../../types'; +import { zodInputDataProvider } from '../../../providers/zod-input-data.provider'; +import { RpcError } from '@klerick/nestjs-json-rpc'; +import { ErrorCode } from '../../../constants'; + +describe('input-data.pipe', () => { + let inputDataPipe: InputDataPipe; + beforeEach(async () => { + const testModuleRef = await Test.createTestingModule({ + providers: [InputDataPipe, zodInputDataProvider], + }).compile(); + + inputDataPipe = testModuleRef.get(InputDataPipe); + }); + + it('Should be ok one item', () => { + const value = { + jsonrpc: '2.0', + id: 1, + params: ['1', '2'], + method: 'TestClass.testMethode', + }; + const expectedResult: PayloadRpcData = { + jsonrpc: '2.0', + id: 1, + params: ['1', '2'], + method: { + methodName: 'testMethode', + spaceName: 'TestClass', + }, + }; + expect(inputDataPipe.transform(value)).toEqual(expectedResult); + }); + + it('Should be ok array', () => { + const value = [ + { + jsonrpc: '2.0', + id: 1, + params: ['1', '2'], + method: 'TestClass.testMethode', + }, + ]; + const expectedResult: PayloadRpcData = [ + { + jsonrpc: '2.0', + id: 1, + params: ['1', '2'], + method: { + methodName: 'testMethode', + spaceName: 'TestClass', + }, + }, + ]; + expect(inputDataPipe.transform(value)).toEqual(expectedResult); + }); + it('Should be error', () => { + expect.assertions(3); + try { + inputDataPipe.transform({}); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe( + ErrorCode[ErrorCodeType.InvalidRequest] + ); + expect((e as RpcError).id).toBe(null); + } + }); + it('Should be error after array', () => { + expect.assertions(3); + try { + inputDataPipe.transform([{}]); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe( + ErrorCode[ErrorCodeType.InvalidRequest] + ); + expect((e as RpcError).id).toBe(null); + } + }); + it('Should be error after array with id', () => { + expect.assertions(3); + const val = [ + { + id: 1, + method: 'TestClass', + }, + ]; + try { + inputDataPipe.transform(val); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe( + ErrorCode[ErrorCodeType.InvalidRequest] + ); + + expect((e as RpcError).id).toBe(val[0].id); + } + }); + it('Should be error after array with id inner', () => { + expect.assertions(3); + const val = [ + { + jsonrpc: '2.0', + id: 1, + params: ['1', '2'], + method: 'TestClass.testMethode', + }, + { + id: 2, + method: 'TestClass', + }, + ]; + try { + inputDataPipe.transform(val); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe( + ErrorCode[ErrorCodeType.InvalidRequest] + ); + + expect((e as RpcError).id).toBe(val[1].id); + } + }); + it('Should be error after array with id', () => { + expect.assertions(3); + const val = { + id: 1, + method: 'TestClass', + }; + try { + inputDataPipe.transform(val); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe( + ErrorCode[ErrorCodeType.InvalidRequest] + ); + + expect((e as RpcError).id).toBe(val.id); + } + }); +}); diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.ts new file mode 100644 index 0000000..68ff6ea --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/pipe/input-data.pipe.ts @@ -0,0 +1,51 @@ +import { Inject, PipeTransform } from '@nestjs/common'; + +import { ZOD_INPUT_DATA } from '../../../constants'; +import { + ZodPayloadRpc, + ErrorCodeType, + PayloadRpcArray, + PayloadRpc, +} from '../../../types'; +import { createError, RpcError } from '../../../utils'; + +export class InputDataPipe + implements PipeTransform +{ + @Inject(ZOD_INPUT_DATA) zodInputData!: ZodPayloadRpc; + + transform(value: unknown): PayloadRpcArray | PayloadRpc { + if (Array.isArray(value)) { + const resultValue: PayloadRpcArray = []; + for (const item of value) { + try { + resultValue.push(this.zodInputData.parse(item)); + } catch (e) { + throw this.getError(item); + } + } + return resultValue; + } else { + try { + return this.zodInputData.parse(value); + } catch (e) { + throw this.getError(value); + } + } + } + + private getError(value: unknown): RpcError { + const error = createError(ErrorCodeType.InvalidRequest); + if ( + typeof value === 'object' && + value !== null && + 'id' in value && + (typeof value['id'] === 'string' || typeof value['id'] === 'number') + ) { + const id = parseInt(`${value['id']}`); + error.id = isNaN(id) ? null : id; + } + + return error; + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.spec.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.spec.ts new file mode 100644 index 0000000..88a0b65 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.spec.ts @@ -0,0 +1,26 @@ +import { Test } from '@nestjs/testing'; +import { ExplorerService } from './explorer.service'; +import { RpcHandler } from '../../../decorators'; + +@RpcHandler() +class TestClass {} + +@RpcHandler() +class Test2Class {} + +describe('explorer.service', () => { + let explorerService: ExplorerService; + beforeEach(async () => { + const testModuleRef = await Test.createTestingModule({ + providers: [ExplorerService, TestClass, Test2Class], + }).compile(); + explorerService = testModuleRef.get(ExplorerService); + }); + + it('explorer', async () => { + const result = explorerService.explore(); + expect(result.length).toBe(2); + expect(result).toContain(TestClass); + expect(result).toContain(Test2Class); + }); +}); diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.ts new file mode 100644 index 0000000..926d776 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/explorer.service.ts @@ -0,0 +1,33 @@ +import { Inject, Injectable, Type } from '@nestjs/common'; +import { ModulesContainer } from '@nestjs/core'; +import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; + +import { JsonRpcMetadataKey } from '../../../constants'; + +@Injectable() +export class ExplorerService { + @Inject(ModulesContainer) + private readonly modulesContainer!: ModulesContainer; + + explore(): Type[] { + const modules = [...this.modulesContainer.values()]; + return modules + .reduce( + (acum, module) => (acum.push(...module.providers.values()), acum), + [] as InstanceWrapper[] + ) + .map((instanceWrapper) => { + const { instance } = instanceWrapper; + if (!instance) { + return undefined; + } + + const metadata = Reflect.getMetadata( + JsonRpcMetadataKey, + instance.constructor + ); + return metadata ? (instance.constructor as Type) : undefined; + }) + .filter((i): i is Type => !!i); + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.spec.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.spec.ts new file mode 100644 index 0000000..b29872f --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.spec.ts @@ -0,0 +1,358 @@ +import { HandlerService } from './handler.service'; +import { Test } from '@nestjs/testing'; +import { ParseIntPipe, ParseBoolPipe } from '@nestjs/common'; +import { ModuleRef } from '@nestjs/core'; + +import { createError, RpcError } from '../../../utils'; +import { mapHandlerStoreProvider, AsyncIterate } from '../../../providers'; +import { ErrorCode, MAP_HANDLER } from '../../../constants'; +import { RpcParamsPipe } from '../../../decorators'; +import { ErrorCodeType, PayloadRpcData } from '../../../types'; + +class RpcTestClass { + rpcTestMethode( + @RpcParamsPipe(ParseIntPipe) firstInputParam: number, + @RpcParamsPipe(ParseIntPipe) secondInputParam: number + ): { firstInputParam: number; secondInputParam: number } { + return { firstInputParam, secondInputParam }; + } + + rpcTest2Methode( + @RpcParamsPipe(ParseIntPipe) firstInputParam: number, + secondInputParam: boolean + ): { firstInputParam: number; secondInputParam: boolean } { + return { firstInputParam, secondInputParam }; + } +} + +describe('handler.service', () => { + let handlerService: HandlerService; + let mapHandler: Map; + let moduleRef: ModuleRef; + beforeEach(async () => { + const testModuleRef = await Test.createTestingModule({ + providers: [HandlerService, mapHandlerStoreProvider, AsyncIterate], + controllers: [ParseIntPipe], + }).compile(); + + handlerService = testModuleRef.get(HandlerService); + mapHandler = testModuleRef.get(MAP_HANDLER); + moduleRef = testModuleRef.get(ModuleRef); + }); + + describe('runRpc', () => { + it('Should be result', async () => { + const params = ['1', '2']; + const jsonrpc = '2.0'; + const handlerServiceCallHandlerSpy = jest + .spyOn(handlerService, 'callHandler') + .mockResolvedValue({ + jsonrpc, + result: params.map((i) => parseInt(i, 10)), + id: null, + }); + const rpcData: PayloadRpcData = { + params, + jsonrpc, + method: { + methodName: 'Test', + spaceName: 'testMethode', + }, + id: 1, + }; + const result = await handlerService.runRpc(rpcData); + expect(result).toEqual({ + jsonrpc, + result: params.map((i) => parseInt(i, 10)), + id: rpcData.id, + }); + expect(handlerServiceCallHandlerSpy).toHaveBeenCalledWith(rpcData); + }); + it('Should be array result', async () => { + const params = ['1', '2']; + const params2 = ['3', '4']; + const jsonrpc = '2.0'; + const rpcData: PayloadRpcData = [ + { + params, + jsonrpc, + method: { + methodName: 'Test', + spaceName: 'testMethode', + }, + id: 1, + }, + { + params: params2, + jsonrpc, + method: { + methodName: 'Test', + spaceName: 'testMethode', + }, + id: 2, + }, + ]; + let i = 0; + const handlerServiceCallHandlerSpy = jest + .spyOn(handlerService, 'callHandler') + .mockImplementation(() => { + return Promise.resolve({ + jsonrpc, + result: rpcData[i].params.map((i) => parseInt(i as any, 10)), + id: null, + } as any).then((r) => { + i++; + return r; + }); + }); + const result = await handlerService.runRpc(rpcData); + expect(result).toEqual( + rpcData.map((i) => ({ + jsonrpc: i.jsonrpc, + result: i.params.map((i) => parseInt(i as any, 10)), + id: i.id, + })) + ); + expect(handlerServiceCallHandlerSpy).toHaveBeenCalledTimes(2); + expect(handlerServiceCallHandlerSpy).toHaveBeenCalledWith(rpcData[0]); + expect(handlerServiceCallHandlerSpy).toHaveBeenCalledWith(rpcData[1]); + }); + + it('Should be Error rpcObject', async () => { + const params = ['1', '2']; + const jsonrpc = '2.0'; + const title = 'Title Error'; + const description = 'Describe Error'; + const handlerServiceCallHandlerSpy = jest + .spyOn(handlerService, 'callHandler') + .mockRejectedValue( + createError(ErrorCodeType.InvalidRequest, title, description) + ); + const rpcData: PayloadRpcData = { + params, + jsonrpc, + method: { + methodName: 'Test', + spaceName: 'testMethode', + }, + id: 1, + }; + const result = await handlerService.runRpc(rpcData); + expect(handlerServiceCallHandlerSpy).toHaveBeenCalledWith(rpcData); + expect(result).toEqual({ + jsonrpc, + error: { + message: ErrorCodeType.InvalidRequest, + code: ErrorCode[ErrorCodeType.InvalidRequest], + data: { title, description }, + }, + id: rpcData.id, + }); + }); + it('Should be Error rpcObject internalError', async () => { + const params = ['1', '2']; + const jsonrpc = '2.0'; + const title = 'Title Error'; + const handlerServiceCallHandlerSpy = jest + .spyOn(handlerService, 'callHandler') + .mockRejectedValue(new Error(title)); + const rpcData: PayloadRpcData = { + params, + jsonrpc, + method: { + methodName: 'Test', + spaceName: 'testMethode', + }, + id: 1, + }; + const result = await handlerService.runRpc(rpcData); + expect(handlerServiceCallHandlerSpy).toHaveBeenCalledWith(rpcData); + expect(result).toEqual({ + jsonrpc, + error: { + message: ErrorCodeType.ServerError, + code: ErrorCode[ErrorCodeType.ServerError], + data: { title }, + }, + id: rpcData.id, + }); + }); + }); + + describe('callHandler', () => { + it('should be error spaceName', async () => { + expect.assertions(2); + try { + await handlerService.callHandler({ + id: 1, + params: [], + jsonrpc: '2.0', + method: { + methodName: 'test', + spaceName: 'NotFoundSpace', + }, + }); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe(-32601); + } + }); + it('should be error method', async () => { + class TestSpaceName {} + mapHandler.set(TestSpaceName.name, new TestSpaceName()); + expect.assertions(2); + try { + await handlerService.callHandler({ + id: 1, + params: [], + jsonrpc: '2.0', + method: { + methodName: 'test', + spaceName: TestSpaceName.name, + }, + }); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe(-32601); + } + }); + it('Should be correct result', async () => { + mapHandler.set(RpcTestClass.name, new RpcTestClass()); + const params = ['3', '4']; + const result = await handlerService.callHandler({ + id: 1, + params, + jsonrpc: '2.0', + method: { + methodName: 'rpcTestMethode', + spaceName: RpcTestClass.name, + }, + }); + + expect(result).toEqual({ + id: null, + jsonrpc: '2.0', + result: { + firstInputParam: parseInt(params[0], 10), + secondInputParam: parseInt(params[1], 10), + }, + }); + }); + it('Should be validate error', async () => { + mapHandler.set(RpcTestClass.name, new RpcTestClass()); + const params = ['sdfsdfsdf', '4']; + expect.assertions(2); + try { + await handlerService.callHandler({ + id: 1, + params, + jsonrpc: '2.0', + method: { + methodName: 'rpcTestMethode', + spaceName: RpcTestClass.name, + }, + }); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + expect((e as RpcError).code).toBe(-32600); + } + }); + it('Should be other error error', async () => { + class TestSpaceName { + rpcTestMethode() { + throw new Error(); + } + } + mapHandler.set(TestSpaceName.name, new TestSpaceName()); + const params = ['sdfsdfsdf', '4']; + expect.assertions(1); + try { + await handlerService.callHandler({ + id: 1, + params, + jsonrpc: '2.0', + method: { + methodName: 'rpcTestMethode', + spaceName: TestSpaceName.name, + }, + }); + } catch (e) { + expect(e).toBeInstanceOf(Error); + } + }); + }); + + describe('getParamsForHandler', () => { + it('should return new params from class pip', async () => { + const params = ['1', '2']; + const params2: [string, boolean] = ['1', true]; + const rpcTestClassInst = new RpcTestClass(); + const result = await handlerService.getParamsForHandler( + rpcTestClassInst, + 'rpcTestMethode', + params + ); + + expect(result).toEqual(params.map((i) => parseInt(i, 10))); + + const result2 = await handlerService.getParamsForHandler( + rpcTestClassInst, + 'rpcTest2Methode', + params2 + ); + expect(result2).toEqual([parseInt(params2[0], 10), params2[1]]); + }); + + it('should be error', async () => { + const params = ['sdfsdf', '2']; + const rpcTestClassInst = new RpcTestClass(); + expect.assertions(1); + try { + await handlerService.getParamsForHandler( + rpcTestClassInst, + 'rpcTestMethode', + params + ); + } catch (e) { + expect(e).toBeInstanceOf(RpcError); + } + }); + }); + + describe('getPipeByType', () => { + it('should return the pipe instance', async () => { + const pipe = new ParseIntPipe(); + const result = await handlerService.getPipeByType(pipe); + expect(result).toBeInstanceOf(ParseIntPipe); + }); + + it('should return the pipe from pipe type has in provider', async () => { + const moduleRefGetSoy = jest.spyOn(moduleRef, 'get'); + const moduleRefCreateSoy = jest.spyOn(moduleRef, 'create'); + const result = await handlerService.getPipeByType(ParseIntPipe); + expect(result).toBeInstanceOf(ParseIntPipe); + expect(moduleRefCreateSoy).toHaveBeenCalledTimes(0); + expect(moduleRefGetSoy).toHaveBeenCalledTimes(1); + }); + + it('should return the pipe from pipe type has not in provider', async () => { + const moduleRefGetSoy = jest.spyOn(moduleRef, 'get'); + const moduleRefCreateSoy = jest.spyOn(moduleRef, 'create'); + const result = await handlerService.getPipeByType(ParseBoolPipe); + expect(result).toBeInstanceOf(ParseBoolPipe); + expect(moduleRefCreateSoy).toHaveBeenCalledTimes(1); + expect(moduleRefGetSoy).toHaveBeenCalledTimes(1); + }); + + it('should return the pipe from pipe type has not in provider twice', async () => { + const moduleRefGetSoy = jest.spyOn(moduleRef, 'get'); + const moduleRefCreateSoy = jest.spyOn(moduleRef, 'create'); + const result = await handlerService.getPipeByType(ParseBoolPipe); + expect(result).toBeInstanceOf(ParseBoolPipe); + const result2 = await handlerService.getPipeByType(ParseBoolPipe); + expect(result2).toBeInstanceOf(ParseBoolPipe); + expect(moduleRefCreateSoy).toHaveBeenCalledTimes(1); + expect(moduleRefGetSoy).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.ts new file mode 100644 index 0000000..5434500 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.ts @@ -0,0 +1,243 @@ +import { + ArgumentMetadata, + BadRequestException, + Inject, + Injectable, + PipeTransform, + Type, +} from '@nestjs/common'; +import { ModuleRef } from '@nestjs/core'; +import { + ErrorCodeType, + PayloadRpc, + PayloadRpcArray, + PayloadRpcData, + RpcResult, +} from '../../../types'; +import { + createError, + fromRpcErrorToRpcErrorObject, + RpcError, +} from '../../../utils'; +import { + ASYNC_ITERATOR_FACTORY, + JsonRpcMetadataKeyParamPipe, + MAP_HANDLER, +} from '../../../constants'; +import { IterateFactory } from '../../../providers'; +import { RpcErrorObject } from '../../../types/error-payloade'; + +type toString = T extends string ? T : never; + +function isArrayData(data: PayloadRpcData): data is PayloadRpcArray { + return Array.isArray(data); +} + +function isTypeTransform( + pipe: Type | PipeTransform +): pipe is PipeTransform { + return !(typeof pipe === 'function' && /^\s*class\s+/.test(pipe.toString())); +} + +function isMethod( + handler: T, + methodName: unknown +): methodName is keyof T { + if (typeof methodName !== 'string') return false; + const methode = Reflect.get(handler, methodName); + return methode && typeof methode === 'function'; +} + +type CallBackReturnType = { + pipe: PipeTransform | undefined; + metatype: ArgumentMetadata; + params: PayloadRpc['params'][number]; + index: number; +}; + +@Injectable() +export class HandlerService { + @Inject(MAP_HANDLER) private readonly mapHandler!: Map; + @Inject(ModuleRef) private readonly moduleRef!: ModuleRef; + @Inject(ASYNC_ITERATOR_FACTORY) + private readonly asyncIterate!: IterateFactory< + PayloadRpc['params'], + ( + params: PayloadRpc['params'][number], + index: number + ) => Promise + >; + + private mapInjectPipe: Map, PipeTransform> = new Map< + Type, + PipeTransform + >(); + + public async runRpc( + data: PayloadRpcData + ): Promise> { + if (isArrayData(data)) { + const result: (RpcResult | RpcErrorObject)[] = []; + for (const item of data) { + const callRpcResult = await this.callRpc(item, item.id); + result.push(callRpcResult); + } + return result; + } else { + return this.callRpc(data, 1); + } + } + + private async callRpc( + rpcData: PayloadRpc, + id: number + ): Promise { + try { + const result = await this.callHandler(rpcData); + return { + ...result, + id, + }; + } catch (e) { + if (e instanceof RpcError) { + return fromRpcErrorToRpcErrorObject(e, id); + } + return fromRpcErrorToRpcErrorObject( + createError(ErrorCodeType.ServerError, (e as Error).message), + id + ); + } + } + + async callHandler(rpcData: PayloadRpc): Promise { + const handler = this.mapHandler.get(rpcData.method.spaceName); + if (!handler) { + throw createError( + ErrorCodeType.MethodNotFound, + `${rpcData.method.spaceName} not found` + ); + } + const methodName = rpcData.method.methodName; + + if (!isMethod(handler, methodName)) { + throw createError( + ErrorCodeType.MethodNotFound, + `${rpcData.method.spaceName}.${rpcData.method.methodName} not found` + ); + } + + const params = await this.getParamsForHandler( + handler, + methodName, + rpcData.params + ); + + const result = await ( + handler[methodName] as ( + ...arg: PayloadRpc['params'] + ) => Promise + )(...params); + const { jsonrpc } = rpcData; + + return { + jsonrpc, + result, + id: null, + }; + } + + async getParamsForHandler( + nameSpaceInst: T, + methodeName: toString, + params: PayloadRpc['params'] + ): Promise { + const pipesMetadata: Record = Reflect.getMetadata( + JsonRpcMetadataKeyParamPipe, + nameSpaceInst.constructor, + methodeName + ); + + const pipeObjectByIndex: Map | PipeTransform> = + new Map(); + + for (const item in pipesMetadata) { + const index = item.split(':').at(-1); + if (!index) { + continue; + } + pipeObjectByIndex.set(parseInt(index, 10), pipesMetadata[item]); + } + + const paramsType = Reflect.getMetadata( + 'design:paramtypes', + nameSpaceInst.constructor.prototype, + methodeName + ) as ArgumentMetadata[]; + + const callbackFunc = async ( + params: PayloadRpc['params'][number], + index: number + ): Promise => { + let pipe = pipeObjectByIndex.get(index); + if (pipe) { + pipe = await this.getPipeByType(pipe); + } + return { + pipe, + metatype: paramsType[index], + params, + index, + }; + }; + + const iterate = this.asyncIterate.createIterator(params, callbackFunc); + const argAfterParse: PayloadRpc['params'] = []; + for await (const paramItem of iterate) { + const { params, pipe, metatype, index } = paramItem; + if (!pipe) { + argAfterParse.push(params); + continue; + } + try { + const transFromParams = await pipe.transform(params, metatype); + argAfterParse.push(transFromParams); + } catch (e) { + throw createError( + e instanceof BadRequestException + ? ErrorCodeType.InvalidRequest + : ErrorCodeType.ServerError, + (e as Error).message, + `Argument: #${index}` + ); + } + } + + return argAfterParse; + } + + async getPipeByType | PipeTransform>( + pipe: T + ): Promise { + let targetPipeTransform: PipeTransform; + if (isTypeTransform(pipe)) { + targetPipeTransform = pipe; + } else { + const hasInMap = this.mapInjectPipe.get(pipe); + if (hasInMap) { + targetPipeTransform = hasInMap; + } else { + try { + return this.moduleRef.get(pipe, { + strict: false, + }); + } catch (e) { + targetPipeTransform = await this.moduleRef.create( + pipe + ); + this.mapInjectPipe.set(pipe, targetPipeTransform); + } + } + } + return targetPipeTransform; + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/index.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/index.ts new file mode 100644 index 0000000..5c1277d --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/index.ts @@ -0,0 +1,2 @@ +export * from './handler.service'; +export * from './explorer.service'; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.spec.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.spec.ts new file mode 100644 index 0000000..b27de31 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.spec.ts @@ -0,0 +1,33 @@ +import { Test } from '@nestjs/testing'; +import { UtilModule } from './util.module'; +import { ExplorerService } from './service'; +import { MAP_HANDLER } from '../../constants'; + +class TestClass {} +class Test2Class {} + +describe('Check util module', () => { + let utilModule: UtilModule; + let explorerService: ExplorerService; + let mapHandler: Map; + beforeEach(async () => { + const testModuleRef = await Test.createTestingModule({ + imports: [UtilModule], + providers: [TestClass, Test2Class], + }).compile(); + + explorerService = testModuleRef.get(ExplorerService); + utilModule = testModuleRef.get(UtilModule); + mapHandler = testModuleRef.get(MAP_HANDLER); + }); + + it('onApplicationBootstrap', async () => { + jest + .spyOn(explorerService, 'explore') + .mockReturnValue([TestClass, Test2Class]); + utilModule.onApplicationBootstrap(); + expect(mapHandler.size).toBe(2); + expect(mapHandler.get(TestClass.name)).toBeInstanceOf(TestClass); + expect(mapHandler.get(Test2Class.name)).toBeInstanceOf(Test2Class); + }); +}); diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.ts new file mode 100644 index 0000000..2e1cc5b --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/util.module.ts @@ -0,0 +1,35 @@ +import { Inject, Module, OnApplicationBootstrap } from '@nestjs/common'; +import { MAP_HANDLER } from '../../constants'; +import { mapHandlerStoreProvider, AsyncIterate } from '../../providers'; + +import { HandlerService, ExplorerService } from './service'; +import { ModuleRef } from '@nestjs/core'; +import { zodInputDataProvider } from '../../providers/zod-input-data.provider'; + +@Module({ + controllers: [], + providers: [ + mapHandlerStoreProvider, + HandlerService, + ExplorerService, + AsyncIterate, + zodInputDataProvider, + ], + exports: [mapHandlerStoreProvider, HandlerService, AsyncIterate], +}) +export class UtilModule implements OnApplicationBootstrap { + @Inject(MAP_HANDLER) private readonly mapHandler!: Map; + @Inject(ExplorerService) private readonly explorerService!: ExplorerService; + @Inject(ModuleRef) private readonly moduleRef!: ModuleRef; + + onApplicationBootstrap() { + const handlerList = this.explorerService.explore(); + for (const handler of handlerList) { + const instance = this.moduleRef.get(handler, { strict: false }); + if (!instance) { + return; + } + this.mapHandler.set(handler.name, instance); + } + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/nestjs-json-rpc.module.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/nestjs-json-rpc.module.ts new file mode 100644 index 0000000..e935678 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/nestjs-json-rpc.module.ts @@ -0,0 +1,37 @@ +import { DynamicModule, Module, Provider } from '@nestjs/common'; +import { RouterModule } from '@nestjs/core'; +import { JsonRpcConfig, TransportType } from './types'; +import { HttpTransportModule, UtilModule } from './modules'; + +@Module({ + controllers: [], + providers: [], + exports: [], +}) +export class NestjsJsonRpcModule { + static forRootAsync(options: JsonRpcConfig): DynamicModule { + const providers: Provider[] = []; + + switch (options.transport) { + case TransportType.HTTP: { + const httpModule = HttpTransportModule.forRoot(providers, [UtilModule]); + return { + module: NestjsJsonRpcModule, + imports: [ + ...(options.imports || []), + httpModule, + RouterModule.register([ + { + path: options.path, + module: HttpTransportModule, + }, + ]), + ], + exports: [httpModule], + }; + } + default: + throw new Error(`Transport ${options.transport} not implement`); + } + } +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/providers/async-iterator.provider.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/async-iterator.provider.ts new file mode 100644 index 0000000..dd0eef7 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/async-iterator.provider.ts @@ -0,0 +1,84 @@ +import { Provider } from '@nestjs/common'; +import { ASYNC_ITERATOR_FACTORY } from '../constants'; +import { PayloadRpc } from '../types'; +import { undefined } from 'zod'; + +type ParamsReturn = R extends (...arg: any) => infer P + ? P extends Promise + ? T extends [infer K, ...any] + ? K + : T + : P + : never; + +export type IterateFactory< + I extends unknown[], + C extends (...arg: any[]) => any +> = { + createIterator: ( + iterateObject: I, + callback: C + ) => { + [Symbol.asyncIterator](): GeneralAsyncIterator; + }; +}; + +class GeneralAsyncIterator< + C extends (...arg: any[]) => any, + K extends unknown[], + T = K[number], + TReturn = ParamsReturn +> { + private counter = 0; + private maxLimit!: number; + + constructor(private iterateObject: K, private callback: C) { + if (!Array.isArray(iterateObject)) { + throw new Error('Expected iterateObject to be an array'); + } + this.maxLimit = iterateObject.length; + } + + async next(): Promise | { done: true }> { + const items = !Array.isArray(this.iterateObject[this.counter]) + ? [this.iterateObject[this.counter]] + : (this.iterateObject[this.counter] as T[]); + items.push(this.counter); + this.counter++; + + if (this.counter <= this.maxLimit) { + return this.callback(...items).then((r: TReturn) => ({ + done: false, + value: r, + })); + } else { + return Promise.resolve({ done: true }); + } + } +} + +export const AsyncIterate: Provider< + IterateFactory< + PayloadRpc['params'], + ( + item: PayloadRpc['params'][number], + index: number + ) => PayloadRpc['params'][number] + > +> = { + provide: ASYNC_ITERATOR_FACTORY, + useFactory: () => ({ + createIterator( + iterateObject: PayloadRpc['params'], + callback: ( + item: PayloadRpc['params'][number], + index: number + ) => PayloadRpc['params'][number] + ) { + return { + [Symbol.asyncIterator]: () => + new GeneralAsyncIterator(iterateObject, callback), + }; + }, + }), +}; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/providers/index.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/index.ts new file mode 100644 index 0000000..2d1906b --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/index.ts @@ -0,0 +1,2 @@ +export * from './async-iterator.provider'; +export * from './map-handler-store.provider'; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/providers/map-handler-store.provider.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/map-handler-store.provider.ts new file mode 100644 index 0000000..87b19b4 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/map-handler-store.provider.ts @@ -0,0 +1,7 @@ +import { ValueProvider } from '@angular/core'; +import { MAP_HANDLER } from '../constants'; + +export const mapHandlerStoreProvider: ValueProvider = { + provide: MAP_HANDLER, + useValue: new Map(), +}; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/providers/zod-input-data.provider.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/zod-input-data.provider.ts new file mode 100644 index 0000000..5e4ce73 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/providers/zod-input-data.provider.ts @@ -0,0 +1,8 @@ +import { ValueProvider } from '@angular/core'; +import { ZOD_INPUT_DATA } from '../constants'; +import { ZPayloadRpc } from '../types'; + +export const zodInputDataProvider: ValueProvider = { + provide: ZOD_INPUT_DATA, + useValue: ZPayloadRpc, +}; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/types/error-code-type.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/types/error-code-type.ts new file mode 100644 index 0000000..def8b9d --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/types/error-code-type.ts @@ -0,0 +1,8 @@ +export enum ErrorCodeType { + ParseError = 'Parse error', + InvalidRequest = 'Invalid request', + MethodNotFound = 'Method not found', + InvalidParams = 'Invalid params', + InternalError = 'Internal error', + ServerError = 'Server error', +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/types/error-payloade.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/types/error-payloade.ts new file mode 100644 index 0000000..161cc64 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/types/error-payloade.ts @@ -0,0 +1,23 @@ +import { z } from 'zod'; + +import { zVersion } from './payloade'; + +const zRpcIdError = z.union([z.number(), z.null()]); +const zRpcErrorData = z.object({ + title: z.string(), + description: z.string().optional(), +}); +const zRpcError = z.object({ + message: z.string(), + code: z.number(), + data: zRpcErrorData.optional(), +}); + +export const ZRpcError = z.object({ + jsonrpc: zVersion, + error: zRpcError, + id: zRpcIdError, +}); + +export type RpcErrorObject = z.infer; +export type RpcErrorData = z.infer; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/types/index.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/types/index.ts new file mode 100644 index 0000000..fbefa40 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/types/index.ts @@ -0,0 +1,5 @@ +export * from './module-options'; +export * from './payloade'; +export * from './error-code-type'; +export * from './utils'; +export * from './error-payloade'; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/types/module-options.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/types/module-options.ts new file mode 100644 index 0000000..86fc93b --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/types/module-options.ts @@ -0,0 +1,25 @@ +import { + DynamicModule, + ForwardReference, + Provider, + Type, +} from '@nestjs/common'; + +export enum TransportType { + HTTP, + WS, +} + +export type HttpTransportConfig = { + transport: TransportType.HTTP; + path: string; +}; + +export type CommonRpcConfig = { + providers?: Provider[]; + imports?: Array< + Type | DynamicModule | Promise | ForwardReference + >; +}; + +export type JsonRpcConfig = CommonRpcConfig & HttpTransportConfig; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/types/payloade.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/types/payloade.ts new file mode 100644 index 0000000..a59c173 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/types/payloade.ts @@ -0,0 +1,68 @@ +import { z } from 'zod'; + +const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); +type Literal = z.infer; +type Json = Literal | { [key: string]: Json } | Json[]; +const jsonSchema: z.ZodType = z.lazy(() => + z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]) +); + +const zParams = z.union([ + z.string(), + z.number(), + z.boolean(), + z.null(), + jsonSchema, +]); + +export const zVersion = z.literal('2.0'); +const zMethod = z.string().transform((params, ctx) => { + const result = params.split('.'); + if (result.length !== 2) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Not a 2 items', + }); + return z.NEVER; + } + return { + spaceName: result[0], + methodName: result[1], + }; +}); + +const zRpcParams = z + .union([z.array(zParams), z.record(zParams)]) + .transform((params) => + Array.isArray(params) ? params : Object.values(params) + ); + +const zRpcId = z.union([ + z.string().regex(/^\d+$/).transform(Number), + z.number(), +]); + +export const ZPayloadRpc = z.object({ + jsonrpc: zVersion, + method: zMethod, + params: zRpcParams, + id: zRpcId, +}); + +export const ZPayloadRpcArray = z.array(ZPayloadRpc).min(1); + +export const ZPayloadRpcData = z.union([ZPayloadRpc, ZPayloadRpcArray]); + +export type ZodPayloadRpc = typeof ZPayloadRpc; + +export type PayloadRpc = z.infer; +export type PayloadRpcArray = z.infer; +export type PayloadRpcData = z.infer; + +export const ZRpcResult = z.object({ + jsonrpc: zVersion, + result: zRpcParams, + id: z.union([zRpcId, z.null()]), +}); + +export type RpcResult = z.infer; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/types/utils.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/types/utils.ts new file mode 100644 index 0000000..5f2cf2c --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/types/utils.ts @@ -0,0 +1 @@ +export type ValueOf = T[keyof T]; diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/utils/error.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/utils/error.ts new file mode 100644 index 0000000..4127cd5 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/utils/error.ts @@ -0,0 +1,45 @@ +import { ErrorCode } from '../constants'; +import { RpcErrorData, RpcErrorObject } from '../types/error-payloade'; + +export class RpcError extends Error { + id: number | null = null; + constructor( + message: keyof typeof ErrorCode, + public code: number, + public data?: RpcErrorData + ) { + super(message); + } +} + +export function createError( + type: keyof typeof ErrorCode, + title?: string, + description?: string +): RpcError { + let data: undefined | RpcErrorData = undefined; + if (title) { + data = { title }; + } + + if (title && description) { + data = { title, description }; + } + + return new RpcError(type, ErrorCode[type], data); +} + +export function fromRpcErrorToRpcErrorObject( + error: RpcError, + id: null | number = null +): RpcErrorObject { + return { + jsonrpc: '2.0', + error: { + message: error.message, + code: error.code, + ...(error.data ? { data: error.data } : {}), + }, + id: error.id ? error.id : id, + }; +} diff --git a/libs/json-rpc/nestjs-json-rpc/src/lib/utils/index.ts b/libs/json-rpc/nestjs-json-rpc/src/lib/utils/index.ts new file mode 100644 index 0000000..93ae819 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/src/lib/utils/index.ts @@ -0,0 +1 @@ +export * from './error'; diff --git a/libs/json-rpc/nestjs-json-rpc/tsconfig.json b/libs/json-rpc/nestjs-json-rpc/tsconfig.json new file mode 100644 index 0000000..8122543 --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "module": "commonjs", + "forceConsistentCasingInFileNames": true, + "strict": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true + }, + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.lib.json" + }, + { + "path": "./tsconfig.spec.json" + } + ] +} diff --git a/libs/json-rpc/nestjs-json-rpc/tsconfig.lib.json b/libs/json-rpc/nestjs-json-rpc/tsconfig.lib.json new file mode 100644 index 0000000..dbf54fd --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/tsconfig.lib.json @@ -0,0 +1,16 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../../dist/out-tsc", + "declaration": true, + "types": ["node"], + "target": "es2021", + "strictNullChecks": true, + "noImplicitAny": true, + "strictBindCallApply": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src/**/*.ts"], + "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"] +} diff --git a/libs/json-rpc/nestjs-json-rpc/tsconfig.spec.json b/libs/json-rpc/nestjs-json-rpc/tsconfig.spec.json new file mode 100644 index 0000000..69a251f --- /dev/null +++ b/libs/json-rpc/nestjs-json-rpc/tsconfig.spec.json @@ -0,0 +1,14 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + }, + "include": [ + "jest.config.ts", + "src/**/*.test.ts", + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/tsconfig.base.json b/tsconfig.base.json index cf0c7f6..c000886 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -15,6 +15,9 @@ "skipDefaultLibCheck": true, "baseUrl": ".", "paths": { + "@klerick/nestjs-json-rpc": [ + "libs/json-rpc/nestjs-json-rpc/src/index.ts" + ], "database": ["libs/database/src/index.ts"], "json-api-nestjs": ["libs/json-api/json-api-nestjs/src/index.ts"], "json-api-nestjs-sdk": ["libs/json-api/json-api-nestjs-sdk/src/index.ts"],