Skip to content

Commit

Permalink
docs(nestjs-json-rpc,nestjs-json-rpc-sdk): Add readme
Browse files Browse the repository at this point in the history
  • Loading branch information
klerick committed Apr 6, 2024
1 parent bd08c75 commit fcbc6b0
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 26 deletions.
63 changes: 42 additions & 21 deletions libs/json-rpc/nestjs-json-rpc-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ npm install @klerick/nestjs-json-rpc-sdk
## Example

Once the installation process is complete, we can import the **RpcFactory**.
For example, we have RPC serve which have service which implement this interface:
For example, we have RPC server which have service which implement this interface:

```typescript
export type InputType = {
Expand All @@ -34,9 +34,9 @@ export type OutputType = {
};

export interface RpcService {
someMethode(firstArg: number): Promise<number>;
someOtherMethode(firstArg: number, secondArgument: number): Promise<string>;
methodeWithObjectParams(a: InputType): Promise<OutputType>;
someMethod(firstArg: number): Promise<number>;
someOtherMethod(firstArg: number, secondArgument: number): Promise<string>;
methodWithObjectParams(a: InputType): Promise<OutputType>;
}
```

Expand All @@ -53,10 +53,10 @@ const { rpc, rpcBatch } = RpcFactory(
false
);

rpc.RpcService.someMethode(1).sibcribe(r => console.log(r))
rpc.RpcService.someMethod(1).sibcribe(r => console.log(r))

const call1 = rpcForBatch.RpcService.someMethode(1);
const call2 = rpcForBatch.RpcService.methodeWithObjectParams({
const call1 = rpcForBatch.RpcService.someMethod(1);
const call2 = rpcForBatch.RpcService.methodWithObjectParams({
a: 1,
b: 2,
});
Expand All @@ -66,7 +66,7 @@ rpcBatch(call1, call2).sibcribe(([result1, result2]) => console.log(result1, res
```
That's all:)

You can use typescript type checking:
You can use typescript for type checking:
```typescript
import {
RpcFactory,
Expand All @@ -87,7 +87,11 @@ const { rpc, rpcBatch } = RpcFactory<MapperRpc>(
false
);
//TS2345: Argument of type string is not assignable to parameter of type number
const call = rpcForBatch.RpcService.someMethode('inccorectParam');
const call = rpcForBatch.RpcService.someMethod('inccorectParam');
//TS2339: Property IncorrectService does not exist on type MapperRpc
const call2 = rpcForBatch.IncorrectService.someMethod(1);
//TS2339: Property incorrectMethod does not exist on type RpcService
const call3 = rpcForBatch.RpcService.incorrectMethod(1);

```

Expand All @@ -111,6 +115,22 @@ const { rpc, rpcBatch } = RpcFactory<MapperRpc>(
false
);
```
Or you can implement your personal factory.

You should implement **HttpAgentFactory** type

```typescript

type Transport<T extends LoopFunc> = (
body: PayloadRpc<T>
) => Observable<RpcResult<T>>;

type HttpAgentFactory<T extends LoopFunc> = (
url: string
) => Transport<T>;
```



if you want to use **Promise** instead of **Observer**

Expand All @@ -129,12 +149,12 @@ const { rpc, rpcBatch, rpcForBatch } = RpcFactory<MapperRpc>(
transport: TransportType.HTTP,
httpAgentFactory: axiosTransportFactory(axios),
},
false
true // need true for use promise as result
);
const result = await rpcForBatch.RpcService.someMethode(1)
const result = await rpcForBatch.RpcService.someMethod(1)

const call1 = rpcForBatch.RpcService.someMethode(1);
const call2 = rpcForBatch.RpcService.methodeWithObjectParams({
const call1 = rpcForBatch.RpcService.someMethod(1);
const call2 = rpcForBatch.RpcService.methodWithObjectParams({
a: 1,
b: 2,
});
Expand All @@ -144,20 +164,21 @@ const [result1, result2] = await rpcBatch(call1, call2);

For use **WebSocket**
```typescript
import axios from 'axios';
import {
RpcFactory,
} from '@klerick/nestjs-json-rpc-sdk';
import { WebSocket } from 'ws';
import { WebSocket as ws } from 'ws';
import { webSocket } from 'rxjs/webSocket';

const someUrl = 'ws://localhost:4200/rpc'
const destroySubject = new Subject<boolean>();
const nativeSocketInstance = webSocket<any>(destroySubject);
const { rpc, rpcBatch, rpcForBatch } = RpcFactory<MapperRpc>(

const { rpc, rpcBatch } = RpcFactory<MapperRpc>(
{
transport: TransportType.WS,
useWsNativeSocket: true, // - Will be use native WebSocket
//nativeSocketImplementation: WebSocket, - if you use NodeJS you can use other implementation
//nativeSocketImplementation: ws, - if you use NodeJS you can use other implementation
rpcHost: `http://localhost:4200`,
rpcPath: `/rpc`,
destroySubject, // - If you need close connection you need call destroySubject.next(true),
Expand All @@ -168,7 +189,6 @@ const { rpc, rpcBatch, rpcForBatch } = RpcFactory<MapperRpc>(
```
You can use **socket.io**
```typescript
import axios from 'axios';
import {
RpcFactory,
} from '@klerick/nestjs-json-rpc-sdk';
Expand All @@ -178,18 +198,18 @@ import { io } from 'socket.io-client';
const someUrl = 'ws://localhost:4200'
const destroySubject = new Subject<boolean>();
const ioSocketInstance = io(someUrl, { path: '/rpc' })
const { rpc, rpcBatch, rpcForBatch } = RpcFactory<MapperRpc>(
const { rpc, rpcBatch } = RpcFactory<MapperRpc>(
{
transport: TransportType.WS,
useWsNativeSocket: false, // - Will be use native WebSocket
useWsNativeSocket: false, // - Will be use socket.io
destroySubject, // - If you need close connection you need call destroySubject.next(true),
ioSocketInstance
},
false
);
```

You can use module for Angular:
You can use Angular module:

```typescript

Expand All @@ -199,6 +219,7 @@ import {
TransportType,
} from '@klerick/nestjs-json-rpc-sdk/json-rpc-sdk.module'
import { Subject } from 'rxjs';
import { io } from 'socket.io-client';
import {
JSON_RPC,
RPC_BATCH,
Expand Down
12 changes: 11 additions & 1 deletion libs/json-rpc/nestjs-json-rpc-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,14 @@ export {
ResultRpcFactoryPromise,
ResultRpcFactory,
} from './lib/factory';
export { RpcConfig, TransportType, ErrorCodeType, RpcError } from './lib/types';
export {
RpcConfig,
TransportType,
ErrorCodeType,
RpcError,
LoopFunc,
HttpAgentFactory,
Transport,
PayloadRpc,
RpcResult,
} from './lib/types';
2 changes: 0 additions & 2 deletions libs/json-rpc/nestjs-json-rpc-sdk/src/lib/types/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ export type PayloadRpc<T extends LoopFunc> = {
id: number;
};

export type IdRequest = () => number;

export type RpcResultObject<T extends LoopFunc> = {
jsonrpc: JsonRpcVersion;
result: ReturnGenericType<T>;
Expand Down
17 changes: 16 additions & 1 deletion libs/json-rpc/nestjs-json-rpc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ export class AppModule {
```
`wsConfig` - is GatewayMetadata from `@nestjs/websockets/interfaces`;

***!!!!***: - NestJs by default using **socket.io** adapter, if you want to use native WebSocket, you should use **WsAdapter**
```typescript
import { WsAdapter } from '@nestjs/platform-ws';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app/app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(new WsAdapter(app));
app.init()
await app.listen(3000);
}
```

To allow service to your RPC server, you should create class and add to providers the root **AppModule**.

```typescript
Expand Down Expand Up @@ -103,6 +117,7 @@ export class AppModule {
}
```
`@RpcHandler` - decorator which mark class as RPC service

`@RpcParamsPipe` - decorator for validate input data,


Expand All @@ -112,7 +127,7 @@ After it, you can call you RPC service:
POST /rpc
```

- **body** - Create new User and add link to address
- **body** - for http request

```json
{"jsonrpc": "2.0", "method": "RpcService.methodeWithObjectParams", "params": {"a": 23}, "id": 1}
Expand Down
19 changes: 19 additions & 0 deletions libs/json-rpc/nestjs-json-rpc/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,25 @@
"codeCoverage": true,
"coverageReporters": ["json-summary"]
}
},
"upload-badge": {
"executor": "nx:run-commands",
"dependsOn": [
{
"target": "test"
}
],
"options": {
"commands": ["node tools/scripts/upload-badge.mjs nestjs-json-rpc"],
"cwd": "./",
"parallel": false,
"outputPath": "{workspaceRoot}/libs/json-rpc/nestjs-json-rpc"
}
},
"nx-release-publish": {
"options": {
"packageRoot": "dist/libs/json-rpc/nestjs-json-rpc"
}
}
},
"tags": []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import { WS_EVENT_NAME } from '../constants';

describe('rpc-ws-error-exception.filter', () => {
describe('WebSocket', () => {
const WebSocketInst = new WebSocket('http://0.0.0.0', {});
const WebSocketInst = new WebSocket(
'wss://demo.piesocket.com/v3/channel_123',
{}
);
let argumentsHost: ArgumentsHost;
let getClient: () => WebSocket;

Expand Down

0 comments on commit fcbc6b0

Please sign in to comment.