{"_id":"@dapplets/openrpc-nestjs-json-rpc","_rev":"2-f0192cac75de1a661804848e104c58e1","name":"@dapplets/openrpc-nestjs-json-rpc","dist-tags":{"latest":"0.0.8"},"versions":{"0.0.7":{"name":"@dapplets/openrpc-nestjs-json-rpc","version":"0.0.7","license":"MIT","_id":"@dapplets/openrpc-nestjs-json-rpc@0.0.7","maintainers":[{"name":"alsakhaev","email":"alsakhaev@gmail.com"},{"name":"dapplets-org","email":"admin@dapplets.org"}],"homepage":"https://github.com/dapplets/openrpc-nestjs-json-rpc#readme","bugs":{"url":"https://github.com/dapplets/openrpc-nestjs-json-rpc/issues"},"dist":{"shasum":"d6c67ba12b30a08aac532787d0c514ed0fe2f181","tarball":"https://registry.npmjs.org/@dapplets/openrpc-nestjs-json-rpc/-/openrpc-nestjs-json-rpc-0.0.7.tgz","fileCount":73,"integrity":"sha512-Vyf6LqxkmtVFiodoLLxczGwO1sU2TIZxTCiCC5+ZD/Qbjzw+r/1ng25LUXkav8zoOGQliQ+1p4Yqwqukeyleug==","signatures":[{"sig":"MEUCIGS7L9ZfZbC4BgbOvQPvJzayEkb4uPnw3kStRnrhwL33AiEAtDy8DEnfVmey3FKPzZQ4LvWMrHlOI4W9++9W5rtXrYw=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":232932},"jest":{"testRegex":".spec.ts$","transform":{"^.+\\.(t|j)s$":"ts-jest"},"testEnvironment":"node","coverageDirectory":"../coverage","moduleFileExtensions":["js","json","ts"]},"main":"dist/index.js","types":"dist/index.d.ts","authors":["hfour","shanejonas"],"gitHead":"1fb47d19f0130168f4370c00b237301db58cf049","scripts":{"test":"yarn prettier:check && jest","build":"tsc -p tsconfig.json","format":"prettier --write \"src/**/*.ts\" \"test/**/*.ts\"","test:cov":"jest --coverage","prepublish":"tsc -p tsconfig.json","test:watch":"jest --watch","prettier:check":"prettier --no-color --check  \"src/**/*.ts\" \"test/**/*.ts\""},"_npmUser":{"name":"dapplets-org","email":"admin@dapplets.org"},"repository":{"url":"git+https://github.com/dapplets/openrpc-nestjs-json-rpc.git","type":"git"},"_npmVersion":"10.9.2","description":"OpenRPC JSON-RPC module for NestJS framework","directories":{},"_nodeVersion":"22.16.0","dependencies":{"zod":"^3.23.8","axios":"^0.21.4","cheerio":"^1.0.0","express":"^4.21.0","reflect-metadata":"^0.2.0","zod-to-json-schema":"^3.23.3","@golevelup/nestjs-discovery":"^4.0.1"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^25.5.4","rxjs":"^7.1.0","ts-jest":"25.2.1","ts-node":"8.6.2","prettier":"^1.19.1","supertest":"^6.3.4","typescript":"^4.9.5","@types/jest":"^25.2.3","@types/node":"^14.18.10","@nestjs/core":"^10.0.0","@nestjs/common":"^10.0.0","@types/express":"^4.17.21","@nestjs/testing":"^10.0.0","github-download":"^0.5.0","@types/supertest":"^2.0.16","@nestjs/microservices":"^10.0.0","@nestjs/platform-express":"^10.0.0"},"peerDependencies":{"@nestjs/core":"^10.0.0","@nestjs/common":"^10.0.0","reflect-metadata":"^0.2.0","@nestjs/platform-express":"^10.0.0"},"_npmOperationalInternal":{"tmp":"tmp/openrpc-nestjs-json-rpc_0.0.7_1749596682126_0.5557474265920379","host":"s3://npm-registry-packages-npm-production"}},"0.0.8":{"name":"@dapplets/openrpc-nestjs-json-rpc","version":"0.0.8","description":"OpenRPC JSON-RPC module for NestJS framework","repository":{"type":"git","url":"git+https://github.com/dapplets/openrpc-nestjs-json-rpc.git"},"authors":["hfour","shanejonas"],"main":"dist/index.js","types":"dist/index.d.ts","license":"MIT","scripts":{"build":"tsc -p tsconfig.json","prepublish":"tsc -p tsconfig.json","prettier:check":"prettier --no-color --check  \"src/**/*.ts\" \"test/**/*.ts\"","format":"prettier --write \"src/**/*.ts\" \"test/**/*.ts\"","test":"yarn prettier:check && jest","test:watch":"jest --watch","test:cov":"jest --coverage"},"dependencies":{"@golevelup/nestjs-discovery":"^4.0.1","axios":"^0.21.4","cheerio":"^1.0.0","express":"^4.21.0","reflect-metadata":"^0.2.0","zod":"^3.23.8","zod-to-json-schema":"^3.23.3"},"devDependencies":{"@nestjs/common":"^10.0.0","@nestjs/core":"^10.0.0","@nestjs/microservices":"^10.0.0","@nestjs/platform-express":"^10.0.0","@nestjs/testing":"^10.0.0","@types/express":"^4.17.21","@types/jest":"^25.2.3","@types/node":"^14.18.10","@types/supertest":"^2.0.16","github-download":"^0.5.0","jest":"^25.5.4","prettier":"^1.19.1","rxjs":"^7.1.0","supertest":"^6.3.4","ts-jest":"25.2.1","ts-node":"8.6.2","typescript":"^4.9.5"},"peerDependencies":{"@nestjs/common":"^10.0.0","@nestjs/core":"^10.0.0","@nestjs/platform-express":"^10.0.0","reflect-metadata":"^0.2.0"},"jest":{"moduleFileExtensions":["js","json","ts"],"testRegex":".spec.ts$","transform":{"^.+\\.(t|j)s$":"ts-jest"},"coverageDirectory":"../coverage","testEnvironment":"node"},"_id":"@dapplets/openrpc-nestjs-json-rpc@0.0.8","gitHead":"4c20f9fe273c7efcef976f1c8b525eeb7f4d4bc9","bugs":{"url":"https://github.com/dapplets/openrpc-nestjs-json-rpc/issues"},"homepage":"https://github.com/dapplets/openrpc-nestjs-json-rpc#readme","_nodeVersion":"22.16.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-54JuQciTzRTBGkWwOd0Lb4+QYoMpWQsy/mcY3T0bTjcAWM4z/1AUjhwITEckPYTSI+pR2Zty+58NJcEmOqjyQg==","shasum":"fa7e195dfba309864124a2712a69ac4934d00bd0","tarball":"https://registry.npmjs.org/@dapplets/openrpc-nestjs-json-rpc/-/openrpc-nestjs-json-rpc-0.0.8.tgz","fileCount":73,"unpackedSize":232992,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIHdn8h623gjcoXaMbrSb6WNB6iGU3nV38Ol48kdW7gMhAiEAvJAiGV55ln4JgAdq4taSWCjK9Z0W0LZvR0HZ46lI/Tw="}]},"_npmUser":{"name":"dapplets-org","email":"admin@dapplets.org"},"directories":{},"maintainers":[{"name":"alsakhaev","email":"alsakhaev@gmail.com"},{"name":"dapplets-org","email":"admin@dapplets.org"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/openrpc-nestjs-json-rpc_0.0.8_1749596934255_0.9829747440522274"},"_hasShrinkwrap":false}},"time":{"created":"2025-06-10T23:04:42.035Z","modified":"2025-06-10T23:08:54.783Z","0.0.7":"2025-06-10T23:04:42.328Z","0.0.8":"2025-06-10T23:08:54.473Z"},"bugs":{"url":"https://github.com/dapplets/openrpc-nestjs-json-rpc/issues"},"license":"MIT","homepage":"https://github.com/dapplets/openrpc-nestjs-json-rpc#readme","repository":{"type":"git","url":"git+https://github.com/dapplets/openrpc-nestjs-json-rpc.git"},"description":"OpenRPC JSON-RPC module for NestJS framework","maintainers":[{"name":"alsakhaev","email":"alsakhaev@gmail.com"},{"name":"dapplets-org","email":"admin@dapplets.org"}],"readme":"# openrpc-nestjs-json-rpc\n[MIT Licensed](LICENSE.md)\n\nA JSON-RPC microservice strategy implementation for NestJS.\n\nCurrently uses HTTP as the transport layer, with plans to add other options as the need arises.\n\nThis is a fork of [nestjs-json-rpc](https://github.com/hfour/nestjs-json-rpc) with the addition of Zod validation and updated dependencies to work with the latest NestJS version.\n\n## Install\n\n`yarn add openrpc-nestjs-json-rpc`\n\n## Usage example\n\nInitialize similar to a regular microservice, but pass a `JsonRpcService` as the strategy option:\n\n```typescript\nconst app = await NestFactory.createMicroservice(ApplicationModule, {\nconst app = NestFactory.create(ApplicationModule);\napp.connectMicroservice({\n  strategy: new JsonRpcServer({\n    path: \"/rpc/v1\",\n    port: 8080\n    server: app.getHttpAdapter()\n  })\n});\nawait app.startAllMicroservicesAsync();\nawait app.listenAsync(3000);\n```\n\nDecorate your controllers with the `@RpcService` and `@RpcMethod` decorators:\n\n```typescript\n@RpcService({\n  namespace: \"test\"\n})\nexport class TestController implements ControllerImplementation<ITestService> {\n  @RpcMethod()\n  public async myMethod(params: any) {\n    console.log(\"The method called was test.myMethod\");\n    return params;\n  }\n}\n```\n\nAll the methods of the service will automatically be added with the name `<namespace>.<method>`.\n\nUse any standard microservice decorators you would like to use:\n\n```typescript\n@UsePipes(TestPipe)\n@UseInterceptors(TestInterceptor)\n@UseGuards(TestGuard)\n@RpcMethod()\npublic async myMethod(params: any) {\n  //...\n}\n```\n\nFor the different types of decorators, see:\n\n- Input validation and transformation - use [NestJS Pipes](https://docs.nestjs.com/pipes)\n- Access control checks, permission, role checks - use [NestJS Guards](https://docs.nestjs.com/guards)\n- Transforming errors into appropriate CodedRpcExceptions (see below) - use [NestJS Exception Filters](https://docs.nestjs.com/exception-filters)\n- All other aspect oriented programming bits (logging, tracing performance measurements etc): use [NestJS Interceptors](https://docs.nestjs.com/interceptors)\n\n### Hybrid Mode\n\nRunning in Hybrid Mode allows you to use a JSON-RPC endpoint alongside an existing Nest.JS application, using the same port. This could be used to run side-by-side with a Healthcheck endpoint, for example. All the decorators remain the same, but the initialization of the microservice should be modified as follows:\n\n```typescript\nconst app = NestFactory.create(ApplicationModule);\napp.connectMicroservice({\n  strategy: new JsonRpcServer({\n    path: \"/rpc/v1\",\n    server: app.getHttpAdapter()\n  })\n});\n\nawait app.startAllMicroservicesAsync();\nawait app.listenAsync(3000);\n```\n\n### Client\n\n`nestjs-json-rpc` also comes with a way to create clients!\n\nSimply initialize the client in any other service, then ask it to create a proxy for `TestService` for the given namespace:\n\n```typescript\n@Injectable()\nclass MyServiceClient {\n  private client = new JsonRpcClient(\"http://localhost:8080/rpc/v1\");\n  private service = this.client.getService<ITestService>(\"test\");\n\n  public doSomething() {\n    // Invoke it just as if its a local service!\n    return this.service.myMethod(paramsHere);\n  }\n}\n```\n\nYou may also pass client headers to be sent with every request, such as the authorization token\n\n```typescript\nlet client = new JsonRpcClient(\"http://localhost:8080/rpc/v1\", {\n  Authorization: `Bearer ${token}`\n});\n```\n\n### End-to-End Testing\n\nYou can write E2E tests with super-test, similar to the [NEST.JS Documentation](https://docs.nestjs.com/fundamentals/testing#end-to-end-testing). This will allow you to write tests without spinning up an HTTP Server (and using a real port).\n\n```typescript\nconst moduleFixture = await Test.createTestingModule({\n  imports: [ApplicationModule]\n})\n  .overrideProvider(ISomeProvider)\n  .useClass(MockSomeProvider)\n  .compile();\n\napp = moduleFixture.createNestApplication();\n\napp.connectMicroservice({\n  strategy: {\n    path: \"/rpc/v1\",\n    server: app.getHttpAdapter()\n  }\n});\n\nawait app.startAllMicroservicesAsync();\nawait app.init();\n\nawait request(app.getHttpServer())\n  .post(\"/rpc/v1\")\n  .send({\n    jsonRpc: \"2.0\",\n    method: \"namespace.method\",\n    params: { foo: \"bar\" }\n  })\n  .expect(200)\n  .expect({\n    jsonrpc: \"2.0\",\n    result: {\n      message: \"Hello World!\"\n    }\n  });\n```\n\n## Context\n\nYou can access additional metadata info about the request (such as headers) using the context.\n\nFor example, to access the `Authorization` header within a guard:\n\n```typescript\n@Injectable()\nclass TestGuard implements CanActivate {\n  canActivate(\n    ctx: ExecutionContext\n  ): boolean | Promise<boolean> | import(\"rxjs\").Observable<boolean> {\n    let authData = ctx\n      .switchToRpc()\n      .getContext<JsonRpcContext>()\n      .getMetadataByKey(\"Authorization\");\n\n    if (authMetadata) {\n      // ... check token\n      return true;\n    }\n    return false;\n  }\n}\n```\n\nTo enable different transports in the future, the metadata mechanism doesn't reveal the metadata transport method. This should allow for the option to implement a different (e.g. TCP based) transport in the future.\n\n## Custom Data\n\nIdeally, you should be using a per-request scope to manage custom data. However, since this NestJS functionality is fairly new and unexplored, `JsonRpcContext` allows you to store and retrieve custom context data in a type-safe way via the property `customData`\n\nContextual data pertaining to a single remote procedure call (a single \"request\") can be stored within this property.\n\nTo use this property, you need to instantiate a `TypesafeKey`.\n\nThe following example decodes and adds user info to the context. JWT is extracted from\nthe RPC request metadata (the Authorization header for our HTTP transport)\n\n```typescript\nimport { TypesafeKey } from \"@hfour/nestjs-json-rpc\";\nimport { UserInfo } from \"./my-code\";\n\nexport const UserInfoKey = new TypesafeKey<UserInfo>(\"myapp:auth:UserInfo\");\n\nexport class TestAuthenticateGuard implements CanActivate {\n  public async canActivate(context: ExecutionContext): Promise<boolean> {\n    const ctx = context.switchToRpc().getContext<JsonRpcContext>();\n    let jwtMetadata = ctx.getMetadataByKey(\"Authorization\");\n    if (!jwtMetadata) return false;\n    const decoded: Result<UserInfo> = jwt.decodeBearer(jwtMetadata);\n    if (decoded.error) return false;\n    ctx.customData.set(UserInfoKey, decoded.result);\n    return true;\n  }\n}\n```\n\nThen you can read it by injecting the context in the RPC method:\n\n```typescript\n  @UseGuards(TestAuthenticateGuard)\n  @RpcMethod()\n  public async getUserInfo(params: {}, @Ctx() ctx: JsonRpcContext) {\n    const userData = ctx.customData.get(UserInfo);\n    return Promise.resolve(data?.name);\n  }\n```\n\nOr you could read the data from another guard, pipe or interceptor.\n\nNote that you are responsible for managing the key space of custom data and ensuring there are no name conflicts.\n\n## Errors\n\n`nestjs-json-rpc` comes with `CodedRpcException`, which as per JSONRPC spec allows you to include an error code and additional data to the error. The error is reconstructed on the client and you can access and check the code and the data there as well.\n\nFeel free to define your own code constants and declare a union of the types in order to be able to discriminate the codes:\n\n```typescript\nfunction isValidationError(e: CodedRpcException);\ntry {\n  await this.service.myMethod(paramsHere);\n} catch (e) {\n  if (e.code === Codes.ValidationError) {\n    // access validation errors here:\n    e.data.validationErrors;\n  }\n}\n```\n\nYou may also implement your own error hierarchy by means of subclassing, but you will not be able to use the `instanceof` checks on the client as errors are not reconstructed. Instead we recommend the following approach:\n\n```typescript\nconst ValidationErrorCode = 400;\ntype ValidationErrorCode = 400;\n\ntype ValidationError = CodedRpcException & {\n  code: ValidationErrorCode;\n  data: {\n    validationErrors: Array<{ path: string; problem: string }>;\n  };\n};\n\nfunction isValidationError(e: any): e is ValidationError {\n  return e instanceof CodedRpcException && e.code === ValidationErrorCode;\n}\n```\n\n\n## Zod Validation\n\n\n### Zod Schema:\n`app.schema.user.ts`\n\n```typescript\nimport z from 'zod';\n\nexport const userSchema = z.object({\n  name: z.string(),\n  age: z.number().optional(),\n});\n\nexport type UserDto = z.infer<typeof userSchema>;\n```\n\n\n### schema usage:\n`app.controller.ts`\n```typescript\nimport { UserDto, userSchema } from './app.schema.user';\nimport { RpcDiscoverService, RpcService } from 'openrpc-nestjs-json-rpc';\nimport { ZodToOpenRPC } from 'openrpc-nestjs-json-rpc';\n\n@RpcService({ namespace: 'test' })\nexport class AppController {\n  constructor(private rpcDiscoverService: RpcDiscoverService) {}\n  @ZodToOpenRPC({\n    schema: userSchema,\n  })\n  public async myMethod(params: UserDto) {\n    console.log('The method called was test.myMethod', params);\n    return this.rpcDiscoverService.getOpenRPCDocument();\n  }\n}\n\n```","readmeFilename":"README.md"}