Compare commits
9 Commits
9a8733a77d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d5d171b280 | |||
| 0d5661d602 | |||
| b440c38e73 | |||
| d936af9793 | |||
| 2fa7b851ff | |||
| 4eac61144f | |||
| 12afcb7a82 | |||
| 40d0e79358 | |||
| 3a4a54d37c |
41
__tests__/e2e/rpc-context.test.ts
Normal file
41
__tests__/e2e/rpc-context.test.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { getRPCContext, RPCContextKey } from "@/core/RPCContext";
|
||||
import { RPCHandler, RPCSession } from "@/index"
|
||||
import { getRandomAvailablePort } from "@/utils/utils";
|
||||
|
||||
describe('rpc-context.test', () => {
|
||||
test('context.session', async () => {
|
||||
const accessed = new WeakMap<RPCSession, string>();
|
||||
const provider = {
|
||||
login(name: string) {
|
||||
const context = getRPCContext(this);
|
||||
if (!context) {
|
||||
throw new Error('context is null');
|
||||
}
|
||||
|
||||
accessed.set(context.session, name);
|
||||
return name;
|
||||
},
|
||||
me() {
|
||||
const context = getRPCContext(this);
|
||||
if (!context) {
|
||||
throw new Error('context is null');
|
||||
}
|
||||
|
||||
return accessed.get(context.session) || 'unknown user';
|
||||
},
|
||||
}
|
||||
|
||||
const server = new RPCHandler();
|
||||
const client = new RPCHandler();
|
||||
|
||||
server.setProvider(provider);
|
||||
const port = await getRandomAvailablePort();
|
||||
await server.listen({ port });
|
||||
|
||||
const session = await client.connect({ url: `http://localhost:${port}` });
|
||||
const api = session.getAPI<typeof provider>();
|
||||
const clientname = 'clientname';
|
||||
await expect(api.login(clientname)).resolves.toBe(clientname);
|
||||
await expect(api.me()).resolves.toBe(clientname);
|
||||
})
|
||||
})
|
||||
@@ -33,8 +33,11 @@ describe('Rpc disconnected test', () => {
|
||||
errorCode: RPCErrorCode.CONNECTION_DISCONNECTED
|
||||
})
|
||||
);
|
||||
await expect(callPromise).rejects.toBeInstanceOf(RPCError);
|
||||
await expect(callPromise).rejects
|
||||
.toHaveProperty('errorCode', RPCErrorCode.CONNECTION_DISCONNECTED);
|
||||
await expect(callPromise).rejects.toMatchObject(
|
||||
expect.objectContaining({
|
||||
constructor: RPCError,
|
||||
errorCode: RPCErrorCode.CONNECTION_DISCONNECTED
|
||||
})
|
||||
);
|
||||
})
|
||||
})
|
||||
|
||||
49
__tests__/e2e/rpc-plugin/rpc-plugin.ctx.session.test.ts
Normal file
49
__tests__/e2e/rpc-plugin/rpc-plugin.ctx.session.test.ts
Normal 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);
|
||||
});
|
||||
})
|
||||
42
__tests__/e2e/rpc-plugin/rpc-plugin.hook.test.ts
Normal file
42
__tests__/e2e/rpc-plugin/rpc-plugin.hook.test.ts
Normal 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);
|
||||
});
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tonecn/typesrpc",
|
||||
"version": "1.0.2",
|
||||
"version": "1.1.0",
|
||||
"description": "A lightweight, type-safe RPC framework for TypeScript with deep nested API support",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
27
src/core/RPCContext.ts
Normal file
27
src/core/RPCContext.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { isObject } from "@/utils/utils";
|
||||
import { RPCSession } from "./RPCSession";
|
||||
|
||||
export interface RPCContext {
|
||||
session: RPCSession;
|
||||
}
|
||||
|
||||
export const RPCContextFlag = Symbol();
|
||||
export const RPCContextKey = '__rpc_context';
|
||||
|
||||
export class RPCContextConstractor {
|
||||
public [RPCContextKey] = RPCContextFlag;
|
||||
constructor(public session: RPCSession) { }
|
||||
}
|
||||
|
||||
export const getRPCContext = (self: unknown): RPCContext | null => {
|
||||
if (!isObject(self)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rpcContext = self[RPCContextKey];
|
||||
if (!isObject(rpcContext) || rpcContext[RPCContextKey] !== RPCContextFlag) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return rpcContext as unknown as RPCContext;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { makeCallPacket, makeCallResponsePacket, parseCallPacket, parseCallRespo
|
||||
import { RPCPacket } from "./RPCPacket";
|
||||
import { EventEmitter } from "@/utils/EventEmitter";
|
||||
import { createHookRunner } from "./RPCPlugin";
|
||||
import { RPCContextConstractor, RPCContextKey } from "./RPCContext";
|
||||
|
||||
function getProviderFunction(provider: RPCProvider, fnPath: string):
|
||||
[(...args: any[]) => Promise<any>, object] | null {
|
||||
@@ -242,6 +243,7 @@ export class RPCSession {
|
||||
|
||||
reject(new RPCError({
|
||||
errorCode: RPCErrorCode.UNKNOWN_ERROR,
|
||||
reason: e instanceof Error ? e.message : `${e}`
|
||||
}))
|
||||
})
|
||||
}
|
||||
@@ -371,7 +373,14 @@ export class RPCSession {
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fn.bind(fnThis)(...args);
|
||||
const result = await fn.bind(new Proxy(fnThis, {
|
||||
get(target, p, receiver) {
|
||||
if (p === RPCContextKey) {
|
||||
return new RPCContextConstractor(instance);
|
||||
}
|
||||
return Reflect.get(target, p, receiver);
|
||||
},
|
||||
}))(...args);
|
||||
return makeResponse({
|
||||
status: 'success',
|
||||
requestPacket: packet,
|
||||
|
||||
@@ -12,6 +12,10 @@ export { SocketConnection } from "./core/SocketConnection";
|
||||
export { SocketServer } from "./core/SocketServer";
|
||||
export { EventEmitter } from "./utils/EventEmitter";
|
||||
|
||||
export { AbstractRPCPlugin, createHookRunner } from './core/RPCPlugin';
|
||||
export type { RPCPlugin, RPCPluginHooks, RPCPluginHooksCtx } from './core/RPCPlugin';
|
||||
export { getRPCContext } from './core/RPCContext';
|
||||
|
||||
export { injectSocketClient } from "./core/SocketClient";
|
||||
export { injectSocketServer } from "./core/SocketServer";
|
||||
import { injectSocketIOImplements } from "./implements/socket.io";
|
||||
|
||||
Reference in New Issue
Block a user