UNPKG

@jsonjoy.com/reactive-rpc

Version:

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

72 lines 2.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypedApiCaller = void 0; const rpc_error_1 = require("rpc-error"); const typed_1 = require("./error/typed"); 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"); class TypedApiCaller extends RpcCaller_1.RpcCaller { constructor({ system, ...rest }) { super({ ...rest, getMethod: (name) => this.get(name), }); this.methods = new Map(); this.req = null; this.res = null; this.system = system; } implement(id, definition_) { const definition = definition_; if (this.methods.has(id)) throw new Error(`Method [id = ${id}] is already implemented.`); const alias = this.system.resolve(id); const type = alias.type; if (!(type instanceof classes_1.FunctionType || type instanceof classes_1.FunctionStreamingType)) throw new Error(`Type [alias = ${alias.id}] is not a function.`); const validator = type.validator('boolean'); const customValidator = definition.validate; const validate = customValidator ? (req) => { const error = validator(req); if (error) throw typed_1.TypedRpcError.valueFromCode(rpc_error_1.RpcErrorCodes.BAD_REQUEST); customValidator(req); } : (req) => { const error = validator(req); if (error) throw typed_1.TypedRpcError.valueFromCode(rpc_error_1.RpcErrorCodes.BAD_REQUEST); }; const isStaticMethodAlias = alias.type instanceof classes_1.FunctionType; const isStreamingMethodAlias = alias.type instanceof classes_1.FunctionStreamingType; const method = isStaticMethodAlias ? new StaticRpcMethod_1.StaticRpcMethod({ ...definition, req: type.req, res: type.res, validate, }) : isStreamingMethodAlias ? new StreamingRpcMethod_1.StreamingRpcMethod({ ...definition, req: type.req, res: type.res, validate, }) : null; if (!method) throw new Error(`Type [alias = ${alias.id}] is not a function.`); this.methods.set(id, method); } get(id) { const method = this.methods.get(id); if (!method) throw typed_1.TypedRpcError.valueFromCode(rpc_error_1.RpcErrorCodes.METHOD_UNK); return method; } } exports.TypedApiCaller = TypedApiCaller; //# sourceMappingURL=TypedApiCaller.js.map