Compare commits

..

2 Commits

3 changed files with 92 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
import { RPCError } from "@/core/RPCError";
import { CallIncomingBeforeCtx, NormalMethodReturn } from "@/core/RPCPlugin";
import { AbstractRPCPlugin, RPCHandler } from "@/index";
import { getRandomAvailablePort, isObject } from "@/utils/utils";
describe('rpc-plugin.ctx.session.test', () => {
const userInfo = 'userinfo';
const users = new WeakMap();
class RPCTestPlugin implements AbstractRPCPlugin {
onCallIncomingBefore(ctx: CallIncomingBeforeCtx): NormalMethodReturn {
if (users.has(ctx.session)) {
return;
}
if (isObject(ctx.request)) {
if (ctx.request.fnPath === 'login') {
users.set(ctx.session, userInfo);
return;
}
}
throw new RPCError({
reason: 'not login'
});
}
}
test('session', async () => {
const server = new RPCHandler();
const loginRes = 'login';
const authRes = 'auth';
const provider = {
login() { return loginRes },
auth() { return authRes }
}
server.setProvider(provider);
server.loadPlugin(new RPCTestPlugin());
const client = new RPCHandler();
const port = await getRandomAvailablePort();
await server.listen({ port });
const session = await client.connect({ url: `http://localhost:${port}` });
const api = session.getAPI<typeof provider>();
await expect(api.auth()).rejects.toMatchObject({ reason: 'not login' });
await expect(api.login()).resolves.toBe(loginRes);
await expect(api.auth()).resolves.toBe(authRes);
});
})

View File

@@ -0,0 +1,42 @@
import { CallIncomingBeforeCtx, CallIncomingCtx, CallOutgoingBeforeCtx, CallOutgoingCtx, NormalMethodReturn } from "@/core/RPCPlugin";
import { AbstractRPCPlugin, RPCHandler } from "@/index";
import { getRandomAvailablePort } from "@/utils/utils";
describe('rpc-plugin.hook.test', () => {
let count = 0;
class RPCTestPlugin implements AbstractRPCPlugin {
onCallIncomingBefore(ctx: CallIncomingBeforeCtx): NormalMethodReturn {
count += 1;
}
onCallIncoming(ctx: CallIncomingCtx): NormalMethodReturn {
count += 2;
}
onCallOutgoingBefore(ctx: CallOutgoingBeforeCtx): NormalMethodReturn {
count += 4;
}
onCallOutgoing(ctx: CallOutgoingCtx): NormalMethodReturn {
count += 8;
}
}
const CountShouldBe = 15;
test('count', async () => {
const server = new RPCHandler();
const provider = {
add(a: number, b: number) { return a + b }
}
server.setProvider(provider);
server.loadPlugin(new RPCTestPlugin());
const client = new RPCHandler();
client.loadPlugin(new RPCTestPlugin());
const port = await getRandomAvailablePort();
await server.listen({ port });
const session = await client.connect({ url: `http://localhost:${port}` });
const api = session.getAPI<typeof provider>();
await expect(api.add(1, 2)).resolves.toBe(3);
expect(count).toBe(CountShouldBe);
});
})

View File

@@ -242,6 +242,7 @@ export class RPCSession {
reject(new RPCError({
errorCode: RPCErrorCode.UNKNOWN_ERROR,
reason: e instanceof Error ? e.message : `${e}`
}))
})
}