Skip to content

Commit bb102fb

Browse files
committed
ci(nestjs-json-rpc-sdk): fix test and create e2e
1 parent d214666 commit bb102fb

File tree

24 files changed

+355
-32
lines changed

24 files changed

+355
-32
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import { INestApplication } from '@nestjs/common';
2+
import {
3+
ResultRpcFactoryPromise,
4+
ErrorCodeType,
5+
RpcError,
6+
} from '@klerick/nestjs-json-rpc-sdk';
7+
8+
import { creatRpcSdk, MapperRpc, run } from '../utils/run-ppplication';
9+
10+
let app: INestApplication;
11+
12+
beforeAll(async () => {
13+
app = await run();
14+
});
15+
16+
afterAll(async () => {
17+
await app.close();
18+
});
19+
20+
describe('Run json rpc:', () => {
21+
let rpc: ResultRpcFactoryPromise<MapperRpc>['rpc'];
22+
let rpcBatch: ResultRpcFactoryPromise<MapperRpc>['rpcBatch'];
23+
let rpcForBatch: ResultRpcFactoryPromise<MapperRpc>['rpcForBatch'];
24+
beforeEach(() => {
25+
({ rpc, rpcBatch, rpcForBatch } = creatRpcSdk());
26+
});
27+
28+
describe('Should be correct response', () => {
29+
it('Should be call one method', async () => {
30+
const input = 1;
31+
const result = await rpc.RpcService.someMethode(input);
32+
expect(result).toBe(input);
33+
});
34+
35+
it('Should be correct response batch', async () => {
36+
const input = 1;
37+
const input2 = {
38+
a: 1,
39+
b: 2,
40+
};
41+
const call1 = rpcForBatch.RpcService.someMethode(input);
42+
const call2 = rpcForBatch.RpcService.methodeWithObjectParams(input2);
43+
44+
const [result1, result2] = await rpcBatch(call1, call2);
45+
expect(result1).toBe(input);
46+
if ('error' in result2) {
47+
throw Error('Return error');
48+
}
49+
expect(result2.d).toEqual(`${input2.a}`);
50+
expect(result2.c).toEqual(`${input2.b}`);
51+
});
52+
});
53+
54+
describe('Check error', () => {
55+
it('Should throw an error ' + ErrorCodeType.MethodNotFound, async () => {
56+
const input = 1;
57+
expect.assertions(6);
58+
try {
59+
// @ts-ignore
60+
await rpc.IncorrectService.incorrectMethode(input);
61+
} catch (e) {
62+
expect(e).toBeInstanceOf(RpcError);
63+
expect((e as RpcError).code).toBe(-32601);
64+
expect((e as RpcError).message).toBe(ErrorCodeType.MethodNotFound);
65+
}
66+
try {
67+
// @ts-ignore
68+
await rpc.RpcService.incorrectMethode(input);
69+
} catch (e) {
70+
expect(e).toBeInstanceOf(RpcError);
71+
expect((e as RpcError).code).toBe(-32601);
72+
expect((e as RpcError).message).toBe(ErrorCodeType.MethodNotFound);
73+
}
74+
});
75+
76+
it('Should throw an error ' + ErrorCodeType.InvalidParams, async () => {
77+
const input = 'llll';
78+
expect.assertions(3);
79+
try {
80+
// @ts-ignore
81+
await rpc.RpcService.someMethode(input);
82+
} catch (e) {
83+
expect(e).toBeInstanceOf(RpcError);
84+
expect((e as RpcError).code).toBe(-32602);
85+
expect((e as RpcError).message).toBe(ErrorCodeType.InvalidParams);
86+
}
87+
});
88+
89+
it('Should throw an error ' + ErrorCodeType.ServerError, async () => {
90+
const input = 5;
91+
expect.assertions(4);
92+
try {
93+
await rpc.RpcService.someMethode(input);
94+
} catch (e) {
95+
expect(e).toBeInstanceOf(RpcError);
96+
expect((e as RpcError).code).toBe(-32099);
97+
expect((e as RpcError).message).toBe(ErrorCodeType.ServerError);
98+
expect((e as RpcError).data.title).toBe('Custom Error');
99+
}
100+
});
101+
});
102+
});

apps/json-api-server-e2e/src/json-api/utils/run-ppplication.ts

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
import { Test } from '@nestjs/testing';
22
import { INestApplication } from '@nestjs/common';
3-
import { NestFactory } from '@nestjs/core';
43
import { adapterForAxios, JsonApiJs } from 'json-api-nestjs-sdk';
4+
import {
5+
RpcFactory,
6+
axiosTransportFactory,
7+
RpcConfig,
8+
} from '@klerick/nestjs-json-rpc-sdk';
9+
import { RpcService } from '@nestjs-json-api/type-for-rpc';
510
import axios from 'axios';
611
import { Logger } from 'nestjs-pino';
712

813
import { AppModule } from '../../../../json-api-server/src/app/app.module';
914

1015
import { JsonConfig } from '../../../../../libs/json-api/json-api-nestjs-sdk/src/lib/types';
16+
import { TransportType } from '@klerick/nestjs-json-rpc-sdk';
1117

1218
export const axiosAdapter = adapterForAxios(axios);
1319
let saveApp: INestApplication;
@@ -45,3 +51,19 @@ export const creatSdk = (config: Partial<JsonConfig> = {}) =>
4551
},
4652
true
4753
);
54+
55+
export type MapperRpc = {
56+
RpcService: RpcService;
57+
};
58+
59+
export const creatRpcSdk = (config: Partial<RpcConfig> = {}) =>
60+
RpcFactory<MapperRpc>(
61+
{
62+
...config,
63+
rpcHost: `http://localhost:${port}`,
64+
rpcPath: `${globalPrefix}/rpc`,
65+
transport: TransportType.HTTP,
66+
httpAgentFactory: axiosTransportFactory(axios),
67+
},
68+
true
69+
);
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Module } from '@nestjs/common';
22
import { NestjsJsonRpcModule, TransportType } from '@klerick/nestjs-json-rpc';
3+
import { RpcService } from './service/rpc.service';
34

45
@Module({
56
imports: [
@@ -8,6 +9,6 @@ import { NestjsJsonRpcModule, TransportType } from '@klerick/nestjs-json-rpc';
89
transport: TransportType.HTTP,
910
}),
1011
],
11-
// providers: [ContestRpc, ParseIntArrayPipe, LineUpSchemaPipe],
12+
providers: [RpcService],
1213
})
1314
export class RpcModule {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import {
2+
InputType,
3+
OutputType,
4+
RpcService as IRpcService,
5+
} from '@nestjs-json-api/type-for-rpc';
6+
7+
import {
8+
createErrorCustomError,
9+
RpcHandler,
10+
RpcParamsPipe,
11+
} from '@klerick/nestjs-json-rpc';
12+
import { ParseIntPipe } from '@nestjs/common';
13+
14+
@RpcHandler()
15+
export class RpcService implements IRpcService {
16+
methodeWithObjectParams(a: InputType): Promise<OutputType> {
17+
return Promise.resolve({
18+
d: `${a.a}`,
19+
c: `${a.b}`,
20+
});
21+
}
22+
23+
someMethode(@RpcParamsPipe(ParseIntPipe) firstArg: number): Promise<number> {
24+
if (firstArg === 5) throw createErrorCustomError(-32099, 'Custom Error');
25+
return Promise.resolve(firstArg);
26+
}
27+
28+
someOtherMethode(firstArg: number, secondArgument: number): Promise<string> {
29+
return Promise.resolve('');
30+
}
31+
}
Original file line numberDiff line numberDiff line change
@@ -1 +1,7 @@
1-
export * from './lib/nestjs-json-rpc-sdk';
1+
export {
2+
axiosTransportFactory,
3+
RpcFactory,
4+
ResultRpcFactoryPromise,
5+
ResultRpcFactory,
6+
} from './lib/factory';
7+
export { RpcConfig, TransportType, ErrorCodeType, RpcError } from './lib/types';

libs/json-rpc/nestjs-json-rpc-sdk/src/lib/factory/rpc.factory.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import { RpcConfig, RpcReturnList, RpcBatch, RpcBatchPromise } from '../types';
22
import { transportFactory } from './transport.factory';
33
import { RpcBatchFactory, rpcProxy, RpcBatchFactoryPromise } from '../utils';
44

5-
type ResultRpcFactory<T extends object> = {
5+
export type ResultRpcFactory<T extends object> = {
66
rpc: RpcReturnList<T, false>;
77
rpcBatch: RpcBatch;
88
};
9-
type ResultRpcFactoryPromise<T extends object> = {
9+
export type ResultRpcFactoryPromise<T extends object> = {
1010
rpc: RpcReturnList<T, true>;
1111
rpcForBatch: RpcReturnList<T, false>;
1212
rpcBatch: RpcBatchPromise;
@@ -30,7 +30,7 @@ export function RpcFactory<T extends object>(
3030

3131
if (usePromise) {
3232
rpc = rpcProxy<RpcReturnList<T, true>>(transport, usePromise);
33-
rpcForBatch = rpcProxy<RpcReturnList<T, false>>(transport, usePromise);
33+
rpcForBatch = rpcProxy<RpcReturnList<T, false>>(transport, false);
3434
return { rpc, rpcForBatch, rpcBatch: RpcBatchFactoryPromise(transport) };
3535
} else {
3636
rpc = rpcProxy<RpcReturnList<T, false>>(transport, usePromise);

libs/json-rpc/nestjs-json-rpc-sdk/src/lib/json-rpc-angular.ts

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import {
2-
Component,
32
inject,
43
InjectionToken,
54
ModuleWithProviders,

libs/json-rpc/nestjs-json-rpc-sdk/src/lib/nestjs-json-rpc-sdk.spec.ts

-7
This file was deleted.

libs/json-rpc/nestjs-json-rpc-sdk/src/lib/nestjs-json-rpc-sdk.ts

-5
This file was deleted.

libs/json-rpc/nestjs-json-rpc-sdk/src/lib/utils/rpc-batch.spec.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,17 @@ describe('rpc-batch', () => {
5858

5959
it('RpcBatchFactoryPromise', async () => {
6060
const transport = jest.fn().mockImplementationOnce((data) => {
61-
expect(data.map((i: any) => i.id)).toEqual([1, 2, 3]);
61+
expect(data.map((i: any) => i.id)).toEqual([4, 5, 6]);
6262
const errorObj = {
6363
error: {
6464
message: 'ErrroMsg',
6565
code: 1,
6666
},
67-
id: 3,
67+
id: 6,
6868
};
6969
return of(
7070
data.map((i: any) => {
71-
if (i.id === 3) {
71+
if (i.id === 6) {
7272
return errorObj;
7373
} else {
7474
return {
@@ -100,7 +100,6 @@ describe('rpc-batch', () => {
100100
) as any;
101101

102102
const [r3, r1, r2] = await rpcBatch(call3, call1, call2);
103-
104103
expect(r3).toBeInstanceOf(RpcError);
105104
expect(r2).toEqual(call2.arg);
106105
expect(r1).toEqual(call1.arg);

libs/json-rpc/nestjs-json-rpc/src/index.ts

+3
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,7 @@ export {
44
fromRpcErrorToRpcErrorObject,
55
createError,
66
RpcError,
7+
createErrorCustomError,
78
} from './lib/utils';
9+
10+
export { RpcHandler, RpcParamsPipe } from './lib/decorators';

libs/json-rpc/nestjs-json-rpc/src/lib/modules/util/service/handler.service.ts

+14-5
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
MAP_HANDLER,
2626
} from '../../../constants';
2727
import { IterateFactory } from '../../../providers';
28-
import { RpcErrorObject } from '../../../types/error-payloade';
28+
import { RpcErrorObject } from '../../../types';
2929

3030
type toString<T> = T extends string ? T : never;
3131

@@ -84,7 +84,7 @@ export class HandlerService {
8484
}
8585
return result;
8686
} else {
87-
return this.callRpc(data, 1);
87+
return this.callRpc(data, data.id);
8888
}
8989
}
9090

@@ -99,6 +99,7 @@ export class HandlerService {
9999
id,
100100
};
101101
} catch (e) {
102+
console.log(e);
102103
if (e instanceof RpcError) {
103104
return fromRpcErrorToRpcErrorObject(e, id);
104105
}
@@ -182,9 +183,17 @@ export class HandlerService {
182183
if (pipe) {
183184
pipe = await this.getPipeByType(pipe);
184185
}
186+
let metatype: ArgumentMetadata = {
187+
type: 'custom',
188+
data: '',
189+
metatype: undefined,
190+
};
191+
if (paramsType && paramsType[index]) {
192+
metatype = paramsType[index];
193+
}
185194
return {
186195
pipe,
187-
metatype: paramsType[index],
196+
metatype,
188197
params,
189198
index,
190199
};
@@ -204,8 +213,8 @@ export class HandlerService {
204213
} catch (e) {
205214
throw createError(
206215
e instanceof BadRequestException
207-
? ErrorCodeType.InvalidRequest
208-
: ErrorCodeType.ServerError,
216+
? ErrorCodeType.InvalidParams
217+
: ErrorCodeType.InternalError,
209218
(e as Error).message,
210219
`Argument: #${index}`
211220
);

libs/json-rpc/nestjs-json-rpc/src/lib/utils/error.ts

+28-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { ErrorCode } from '../constants';
22
import { RpcErrorData, RpcErrorObject } from '../types/error-payloade';
3+
import { ErrorCodeType } from '../types';
34

45
export class RpcError extends Error {
56
id: number | null = null;
@@ -12,11 +13,10 @@ export class RpcError extends Error {
1213
}
1314
}
1415

15-
export function createError(
16-
type: keyof typeof ErrorCode,
16+
function getErrorData(
1717
title?: string,
1818
description?: string
19-
): RpcError {
19+
): undefined | RpcErrorData {
2020
let data: undefined | RpcErrorData = undefined;
2121
if (title) {
2222
data = { title };
@@ -25,8 +25,32 @@ export function createError(
2525
if (title && description) {
2626
data = { title, description };
2727
}
28+
return data;
29+
}
2830

29-
return new RpcError(type, ErrorCode[type], data);
31+
export function createErrorCustomError(
32+
code: number,
33+
title?: string,
34+
description?: string
35+
): RpcError {
36+
const absCode = Math.abs(code);
37+
let resultCode = 3200;
38+
if (code < 0 && absCode > 3200 && absCode <= 32099) {
39+
resultCode = code;
40+
}
41+
42+
return new RpcError(
43+
ErrorCodeType.ServerError,
44+
resultCode,
45+
getErrorData(title, description)
46+
);
47+
}
48+
export function createError(
49+
type: keyof typeof ErrorCode,
50+
title?: string,
51+
description?: string
52+
): RpcError {
53+
return new RpcError(type, ErrorCode[type], getErrorData(title, description));
3054
}
3155

3256
export function fromRpcErrorToRpcErrorObject(

0 commit comments

Comments
 (0)