Nest.js implementation of JSON-RPC 2.0 built on top of jayson
$ npm install nest-jayson
- Nest.js with express.js
Register JsonRpcModule in app.module.ts
@Module({
imports: [
JsonRpcModule.forRoot({
middlewares: [],
}),
],
})
export class AppModule {}
Create a controller with @JsonRpcController
decorator
@JsonRpcController('vaccination')
export class VaccinationController {
}
Create a method with @JsonRpcMethod
decorator,
express Request object can be acquired by using @Req
decorator,
and JSON-RPC params
object can be accessed with @Body
decorator.
@JsonRpcController('vaccination')
export class VaccinationController {
@JsonRpcMethod('getVaccination')
getVaccination(@Body request: any, @Req req: Request);
}
Invoke the registered method by calling controller.methodName
with the JSON-RPC params
object as the argument.
{
"jsonrpc": "2.0",
"method": "vaccination.getVaccination",
"params": {
"secureNo": "76481"
},
"id": "2"
}
Middleware is a nestjs provider that implements the JsonRpcMiddleware
interface, middleware can intercept the request before it reaches the controller method.
Use callback
method to return the response immediately, or call next
method to pass the request.
As middlewares are nestjs provider, it can be injected with other providers.
import { JSONRPCCallbackType, JSONRPCResultLike } from 'jayson';
import { Request } from 'express';
import { JsonRpcMiddleware, JsonRpcMiddlewareInterface } from 'nestjs-jayson';
@JsonRpcMiddleware()
export class CacheMiddleware implements JsonRpcMiddlewareInterface {
async use(
req: Request,
callback: JSONRPCCallbackType,
next: (err: any) => void
): Promise<void> {
const result = this.cache.get();
if (result) {
callback(null, result as JSONRPCResultLike);
} else next(null);
}
}
Register the middleware in the JsonRpcModule.forRoot
method by providing method filters and the middleware provider.
Use *.*
to match all methods in all controllers, or controllerName.*
to match all methods in a specific controller.
Even *.methodName
can be used to match a specific method in all controllers.
Middlewares are applied in order of registration.
@Module({
imports: [
JsonRpcModule.forRoot({
middlewares: [
{
methods: ['*.*'],
middleware: AuthMiddleware,
},
],
}),
],
})
nestjs-jayson provides error handling capabilities in order to provide proper JSON-RPC error response.
Distributed under the MIT License