UNPKG

@jsonjoy.com/reactive-rpc

Version:

Reactive-RPC is a library for building reactive APIs over WebSocket, HTTP, and other RPCs.

76 lines 2.79 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypeRouterCaller = void 0; const RpcError_1 = require("./error/RpcError"); const RpcCaller_1 = require("./RpcCaller"); const classes_1 = require("@jsonjoy.com/json-type/lib/type/classes"); const StaticRpcMethod_1 = require("../methods/StaticRpcMethod"); const StreamingRpcMethod_1 = require("../methods/StreamingRpcMethod"); const typed_1 = require("./error/typed"); class TypeRouterCaller extends RpcCaller_1.RpcCaller { constructor({ router, ...rest }) { super({ ...rest, getMethod: (name) => this.get(name), }); this.methods = new Map(); this.req = null; this.res = null; this.router = router; this.system = router.system; } get(id) { let method = this.methods.get(id); if (method) return method; const fn = this.router.routes[id]; if (!fn || !(fn instanceof classes_1.FunctionType || fn instanceof classes_1.FunctionStreamingType)) return undefined; const validator = fn.req.validator('object'); const requestSchema = fn.req.getSchema(); const isRequestVoid = requestSchema.kind === 'const' && requestSchema.value === undefined; const validate = isRequestVoid ? () => { } : (req) => { const error = validator(req); if (error) { const message = error.message + (Array.isArray(error?.path) ? ' Path: /' + error.path.join('/') : ''); throw typed_1.TypedRpcError.value(RpcError_1.RpcError.validation(message, error)); } }; method = fn instanceof classes_1.FunctionType ? new StaticRpcMethod_1.StaticRpcMethod({ req: fn.req, res: fn.res, validate, call: fn.singleton, }) : new StreamingRpcMethod_1.StreamingRpcMethod({ req: fn.req, res: fn.res, validate, call$: fn.singleton, }); this.methods.set(id, method); return method; } async call(id, request, ctx) { return super.call(id, request, ctx); } async callSimple(id, request, ctx = {}) { try { const res = await this.call(id, request, ctx); return res.data; } catch (err) { const error = err; throw error.data; } } call$(id, request, ctx) { return super.call$(id, request, ctx); } } exports.TypeRouterCaller = TypeRouterCaller; //# sourceMappingURL=TypeRouterCaller.js.map