加入插件及调用上下文 #1

Merged
tone merged 17 commits from dev into main 2025-12-02 15:48:35 +08:00
3 changed files with 77 additions and 1 deletions
Showing only changes of commit d936af9793 - Show all commits

View 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);
})
})

27
src/core/RPCContext.ts Normal file
View 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;
}

View File

@@ -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 {
@@ -372,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,