@tuodan/jsonrpc
v1.0.16
Published
JSON RPC module for NestJS framework
Downloads
22
Readme
NestJS JSON RPC package - jsonrpc npm package
Implemented JSON RPC specification
Contents
- Install
- Import module
- How to use simple handler
- How to use multiple handlers in one class
- Decorators description
- Samples
- Changelog
Install
npm i --save @tuodan/jsonrpc
Import module
Import module RpcModule from @tuodan/jsonrpc, example
JsonRpcModule.forRoot({
path: '/rpc', // path to RPC
});How to use simple handler
Create simple RPC handler
Create handler
create RPC handler
import {
RpcId,
RpcPayload,
RpcVersion,
RpcMethod,
IRpcHandler,
RpcHandler,
} from '@tuodan/jsonrpc';
@RpcPackage({
method: 'test',
})
export class TestHandler implements IRpcHandler<Payload> {
public async invoke(
@RpcPayload() payload: Payload,
@RpcVersion() version: string,
@RpcId() id: number | string,
@RpcMethod() method: string,
) {
return payload;
}
}Add to providers
Add TestHandler to providers array
Test with cURL
Every request to RPC is POST method and response status = 200
Test with curl
curl -X POST "http://localhost:3000/rpc" -H "accept: application/json" -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "test", "id": 2}'How to use multiple handlers in one class
Create multiple RPC handler in one class
Create handlers
Create RPC class handler
import {
RpcId,
RpcPayload,
RpcVersion,
RpcMethod,
RpcMethodHandler,
RpcHandler,
} from '@tuodan/jsonrpc';
@RpcPackage({
method: 'contact',
})
export class ContactHandler {
@Rpc('add')
public async add(
@RpcPayload() payload: Payload,
@RpcVersion() version: string,
@RpcId() id: number | string,
@RpcMethod() method: string,
) {
return payload;
}
@Rpc('delete')
public async delete(
@RpcPayload() payload: Payload,
@RpcVersion() version: string,
@RpcId() id: number | string,
@RpcMethod() method: string,
) {
return payload;
}
}Add to providers
Add ContactHandler to providers array
Test with cURL
Every request to RPC is POST method and response status = 200
Test with curl contact.add
curl -X POST "http://localhost:3000/rpc" -H "accept: application/json" -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "contact.add", "id": 2}'Test with curl contact.delete
curl -X POST "http://localhost:3000/rpc" -H "accept: application/json" -H "Content-Type: application/json" -d '{"jsonrpc": "2.0", "method": "contact.delete", "id": 2}'Decorators description
| field | decorator | description | required | other |
| --------- | --------------- | ----------------------- | -------- | --------------------------------------------------------------- |
| params | @RpcPayload() | get payload ( params ) | false | use pipes... |
| jsonrpc | @RpcVersion() | get rpc version | true | use pipes... |
| method | @RpcMethod() | get rpc version | true | use pipes... |
| id | @RpcId() | get client operation id | false | if not send - response not send, RPC notification. use pipes... |
Samples
See examples in samples folder
