Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nestjs-json-rpc): default transport for rpc #78

Merged
merged 16 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ jobs:
key: ${{ runner.os }}-nx-${{ steps.branch-names.outputs.current_branch }}
- run: git branch --track main origin/master
- name: Test and build
run: npx nx affected -t test build --parallel=3 --exclude='json-api-front,json-api-server,json-api-server-e2e,json-shared-type,database,@nestjs-json-api/source'
env:
NX_REJECT_UNKNOWN_LOCAL_CACHE: 0
run: npx nx affected -t test build --parallel=3 --exclude='json-api-front,json-api-server,json-api-server-e2e,json-shared-type,database,@nestjs-json-api/source,type-for-rpc'
- name: Save cached .nx
id: cache-dependencies-save
uses: actions/cache/save@v4
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ jobs:
.nx
key: ${{ runner.os }}-nx-master
- run: npx nx affected -t build --parallel=3 --exclude='json-api-front,json-api-server,json-api-server-e2e,shared-utils,json-shared-type,database'
- run: ls -l ./dist/libs/json-api/json-api-nestjs-sdk
- name: Publish packages
run: npx nx release publish
shell: bash
Expand Down
28 changes: 0 additions & 28 deletions .verdaccio/config.yml

This file was deleted.

2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

- *[json-api-nestjs](https://github.com/klerick/nestjs-json-api/tree/master/libs/json-api/json-api-nestjs)* - plugin for create CRUD overs JSON API
- *[json-api-nestjs-sdk](https://github.com/klerick/nestjs-json-api/tree/master/libs/json-api/json-api-nestjs-sdk)* - tool for client, call api over *json-api-nestjs*
- *[nestjs-json-rpc](https://github.com/klerick/nestjs-json-api/tree/master/libs/json-rpc/nestjs-json-rpc)* - plugin for create RPC server using [JSON-RPC](https://www.jsonrpc.org/)
- *[nestjs-json-rpc-sdk](https://github.com/klerick/nestjs-json-api/tree/master/libs/json-rpc/nestjs-json-rpc-sdk)* - tool for client, call RPC server *nestjs-json-rpc*
- *json-api-nestjs-acl* - tool for acl over *json-api-nestjs*(coming soon...)
## Installation

Expand Down
5 changes: 5 additions & 0 deletions apps/json-api-front/proxy.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,10 @@
"/api": {
"target": "http://localhost:3000",
"secure": false
},
"/rpc": {
"target": "http://localhost:3000",
"secure": false,
"ws": true
}
}
40 changes: 31 additions & 9 deletions apps/json-api-front/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,19 @@ import { Component, inject, OnInit } from '@angular/core';
import { NxWelcomeComponent } from './nx-welcome.component';
import { JsonApiSdkService } from 'json-api-nestjs-sdk';
import { AtomicFactory } from 'json-api-nestjs-sdk/json-api-nestjs-sdk.module';
import {
JSON_RPC,
RPC_BATCH,
Rpc,
} from '@klerick/nestjs-json-rpc-sdk/json-rpc-sdk.module';

import { RpcService as IRpcService } from '@nestjs-json-api/type-for-rpc';
import { switchMap } from 'rxjs';

type RpcMap = {
RpcService: IRpcService;
};

@Component({
standalone: true,
imports: [NxWelcomeComponent],
Expand All @@ -14,14 +25,25 @@ import { switchMap } from 'rxjs';
export class AppComponent implements OnInit {
private JsonApiSdkService = inject(JsonApiSdkService);
private atomicFactory = inject(AtomicFactory);
private rpc = inject<Rpc<RpcMap>>(JSON_RPC);
private rpcBatch = inject(RPC_BATCH);

ngOnInit(): void {
// this.JsonApiSdkService.getAll(class Users {}, {
// page: {
// size: 2,
// number: 1,
// },
// }).subscribe((r) => console.log(r));
const rpc1 = this.rpc.RpcService.someMethode(1);

const rpc2 = this.rpc.RpcService.methodeWithObjectParams({
a: 1,
b: 1,
});

this.rpcBatch(rpc2, rpc1).subscribe(([r2, r1]) => console.log(r1, r2));

this.JsonApiSdkService.getAll(class Users {}, {
page: {
size: 2,
number: 1,
},
}).subscribe((r) => console.log(r));

class Addresses {
id = 1;
Expand Down Expand Up @@ -54,9 +76,9 @@ export class AppComponent implements OnInit {

const tmpUsers = new Users();
tmpUsers.id = 1;
// this.JsonApiSdkService.getRelationships(tmpUsers, 'addresses').subscribe(
// (r) => console.log(r)
// );
this.JsonApiSdkService.getRelationships(tmpUsers, 'addresses').subscribe(
(r) => console.log(r)
);

const roles = new Roles();
roles.id = 10000;
Expand Down
65 changes: 64 additions & 1 deletion apps/json-api-front/src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,60 @@
import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import {
ApplicationConfig,
importProvidersFrom,
InjectionToken,
} from '@angular/core';
import { JsonApiAngular } from 'json-api-nestjs-sdk/json-api-nestjs-sdk.module';
import {
JsonRpcAngular,
JsonRpcAngularConfig,
TransportType,
} from '@klerick/nestjs-json-rpc-sdk/json-rpc-sdk.module';
import { Subject } from 'rxjs';
import { webSocket } from 'rxjs/webSocket';
import { io } from 'socket.io-client';

const destroySubject = new Subject<boolean>();
setTimeout(() => {
console.log('Disconnect');
destroySubject.next(true);
destroySubject.complete();
}, 5000);
const destroySubjectToken = new InjectionToken('destroySubjectToken', {
factory: () => destroySubject,
});
destroySubject.subscribe((r) => console.log(r));
const tokenSocketInst = new InjectionToken('tokenSocketInst', {
factory: () => webSocket('ws://localhost:4200/rpc'),
});

const tokenIoSocketInst = new InjectionToken('tokenIoSocketInst', {
factory: () => io('http://localhost:3000', { path: '/rpc' }),
});

const httpConfig: JsonRpcAngularConfig = {
transport: TransportType.HTTP,
rpcPath: '/api/rpc',
rpcHost: 'http://localhost:4200',
};
const wsConfig: JsonRpcAngularConfig = {
transport: TransportType.WS,
useWsNativeSocket: true,
rpcPath: 'rpc',
rpcHost: 'ws://localhost:4200',
destroySubjectToken,
};
const wsConfigWithToken: JsonRpcAngularConfig = {
transport: TransportType.WS,
useWsNativeSocket: true,
tokenSocketInst,
destroySubjectToken,
};
const ioConfig: JsonRpcAngularConfig = {
transport: TransportType.WS,
useWsNativeSocket: false,
destroySubjectToken,
tokenSocketInst: tokenIoSocketInst,
};

export const appConfig: ApplicationConfig = {
providers: [
Expand All @@ -11,5 +66,13 @@ export const appConfig: ApplicationConfig = {
operationUrl: 'operation',
})
),
importProvidersFrom(
JsonRpcAngular.forRoot(
// httpConfig
// wsConfig
// wsConfigWithToken,
ioConfig
)
),
],
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { FilterOperand, JsonSdkPromise } from 'json-api-nestjs-sdk';
import { Addresses, CommentKind, Comments, Roles, Users } from 'database';
import { faker } from '@faker-js/faker';
import { getUser } from '../utils/data-utils';
import { run, creatSdk } from '../utils/run-ppplication';
import { run, creatSdk } from '../utils/run-application';

let app: INestApplication;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { FilterOperand, JsonSdkPromise } from 'json-api-nestjs-sdk';
import { AxiosError } from 'axios';
import { Users } from 'database';

import { run, creatSdk } from '../utils/run-ppplication';
import { run, creatSdk } from '../utils/run-application';

let app: INestApplication;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { BookList, Users } from 'database';
import { AxiosError } from 'axios';
import { faker } from '@faker-js/faker';
import { lastValueFrom } from 'rxjs';
import { creatSdk, run, axiosAdapter } from '../utils/run-ppplication';
import { creatSdk, run, axiosAdapter } from '../utils/run-application';

let app: INestApplication;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { faker } from '@faker-js/faker';

import { FilterOperand, JsonSdkPromise } from 'json-api-nestjs-sdk';
import { getUser } from '../utils/data-utils';
import { creatSdk, run } from '../utils/run-ppplication';
import { creatSdk, run } from '../utils/run-application';

let app: INestApplication;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Addresses, CommentKind, Comments, Users } from 'database';
import { faker } from '@faker-js/faker';
import { JsonSdkPromise } from 'json-api-nestjs-sdk';

import { creatSdk, run } from '../utils/run-ppplication';
import { creatSdk, run } from '../utils/run-application';

let app: INestApplication;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Addresses, BookList, CommentKind, Comments, Users } from 'database';
import { faker } from '@faker-js/faker';
import { JsonSdkPromise } from 'json-api-nestjs-sdk';

import { creatSdk, run } from '../utils/run-ppplication';
import { creatSdk, run } from '../utils/run-application';
import { INestApplication } from '@nestjs/common';
let app: INestApplication;

Expand Down
102 changes: 102 additions & 0 deletions apps/json-api-server-e2e/src/json-api/json-rpc/run-json-rpc.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { INestApplication } from '@nestjs/common';
import {
ResultRpcFactoryPromise,
ErrorCodeType,
RpcError,
} from '@klerick/nestjs-json-rpc-sdk';

import { creatRpcSdk, MapperRpc, run } from '../utils/run-application';

let app: INestApplication;

beforeAll(async () => {
app = await run();
});

afterAll(async () => {
await app.close();
});

describe('Run json rpc:', () => {
let rpc: ResultRpcFactoryPromise<MapperRpc>['rpc'];
let rpcBatch: ResultRpcFactoryPromise<MapperRpc>['rpcBatch'];
let rpcForBatch: ResultRpcFactoryPromise<MapperRpc>['rpcForBatch'];
beforeEach(() => {
({ rpc, rpcBatch, rpcForBatch } = creatRpcSdk());
});

describe('Should be correct response', () => {
it('Should be call one method', async () => {
const input = 1;
const result = await rpc.RpcService.someMethode(input);
expect(result).toBe(input);
});

it('Should be correct response batch', async () => {
const input = 1;
const input2 = {
a: 1,
b: 2,
};
const call1 = rpcForBatch.RpcService.someMethode(input);
const call2 = rpcForBatch.RpcService.methodeWithObjectParams(input2);

const [result1, result2] = await rpcBatch(call1, call2);
expect(result1).toBe(input);
if ('error' in result2) {
throw Error('Return error');
}
expect(result2.d).toEqual(`${input2.a}`);
expect(result2.c).toEqual(`${input2.b}`);
});
});

describe('Check error', () => {
it('Should throw an error ' + ErrorCodeType.MethodNotFound, async () => {
const input = 1;
expect.assertions(6);
try {
// @ts-ignore
await rpc.IncorrectService.incorrectMethode(input);
} catch (e) {
expect(e).toBeInstanceOf(RpcError);
expect((e as RpcError).code).toBe(-32601);
expect((e as RpcError).message).toBe(ErrorCodeType.MethodNotFound);
}
try {
// @ts-ignore
await rpc.RpcService.incorrectMethode(input);
} catch (e) {
expect(e).toBeInstanceOf(RpcError);
expect((e as RpcError).code).toBe(-32601);
expect((e as RpcError).message).toBe(ErrorCodeType.MethodNotFound);
}
});

it('Should throw an error ' + ErrorCodeType.InvalidParams, async () => {
const input = 'llll';
expect.assertions(3);
try {
// @ts-ignore
await rpc.RpcService.someMethode(input);
} catch (e) {
expect(e).toBeInstanceOf(RpcError);
expect((e as RpcError).code).toBe(-32602);
expect((e as RpcError).message).toBe(ErrorCodeType.InvalidParams);
}
});

it('Should throw an error ' + ErrorCodeType.ServerError, async () => {
const input = 5;
expect.assertions(4);
try {
await rpc.RpcService.someMethode(input);
} catch (e) {
expect(e).toBeInstanceOf(RpcError);
expect((e as RpcError).code).toBe(-32099);
expect((e as RpcError).message).toBe(ErrorCodeType.ServerError);
expect((e as RpcError).data.title).toBe('Custom Error');
}
});
});
});
Loading
Loading