feat: add RPCContext

This commit is contained in:
2025-12-02 15:03:33 +08:00
parent 2fa7b851ff
commit d936af9793
3 changed files with 77 additions and 1 deletions

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