UNPKG

@jsonjoy.com/reactive-rpc

Version:

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

75 lines 2.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ObjectValueCaller = 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 printTree_1 = require("sonic-forest/lib/print/printTree"); const StaticRpcMethod_1 = require("../methods/StaticRpcMethod"); const StreamingRpcMethod_1 = require("../methods/StreamingRpcMethod"); class ObjectValueCaller extends RpcCaller_1.RpcCaller { constructor({ router: value, ...rest }) { super({ ...rest, getMethod: (name) => this.get(name), }); this.methods = new Map(); this.router = value; const system = value.type.system; if (!system) throw new Error('NO_SYSTEM'); this.system = system; } get(id) { let method = this.methods.get(id); if (method) return method; const fn = this.router.get(id); if (!fn || !(fn.type instanceof classes_1.FunctionType || fn.type instanceof classes_1.FunctionStreamingType)) { return undefined; } const fnType = fn.type; const { req, res } = fnType; const call = fn.data; const validator = fnType.req.validator('object'); const requestSchema = fnType.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 RpcError_1.RpcError.validation(message, error); } }; method = fnType instanceof classes_1.FunctionType ? new StaticRpcMethod_1.StaticRpcMethod({ req, res, validate, call }) : new StreamingRpcMethod_1.StreamingRpcMethod({ req, res, validate, call$: call }); 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); } toString(tab = '') { return (`${this.constructor.name}` + (0, printTree_1.printTree)(tab, [(tab) => this.router.toString(tab), (tab) => this.system.toString(tab)])); } } exports.ObjectValueCaller = ObjectValueCaller; //# sourceMappingURL=ObjectValueCaller.js.map