UNPKG

@foxglove/xmlrpc

Version:

TypeScript library implementing an XMLRPC client and server with pluggable server backend

94 lines 3.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.XmlRpcServer = void 0; const Deserializer_1 = require("./Deserializer"); const Serializer_1 = require("./Serializer"); const XmlRpcFault_1 = require("./XmlRpcFault"); // Create an XML-RPC server with a user-supplied HTTP(S) implementation class XmlRpcServer { constructor(server) { this.xmlRpcHandlers = new Map(); this._requestHandler = async (req) => { let methodName; let args; try { const deserializer = new Deserializer_1.Deserializer(); [methodName, args] = await deserializer.deserializeMethodCall(req.body); } catch (err) { return { statusCode: 500, statusMessage: `deserializeMethodCall failed: ${String(err)}`, }; } let body; if (methodName === "system.multicall") { if (!Array.isArray(args) || args.length !== 1 || !Array.isArray(args[0])) { body = (0, Serializer_1.serializeFault)(new XmlRpcFault_1.XmlRpcFault("Invalid system.multicall", Serializer_1.XmlRpcError.INVALID_PARAMS_ERROR)); } else { const calls = args[0]; const responses = await Promise.all( // eslint-disable-next-line @typescript-eslint/promise-function-async calls.map((c) => this._methodCallHandler(c.methodName, c.params))); const allResponses = responses.map((res) => { if (res instanceof XmlRpcFault_1.XmlRpcFault) { return { faultCode: res.faultCode ?? Serializer_1.XmlRpcError.APPLICATION_ERROR, faultString: res.faultString ?? res.message, }; } else { return [res]; } }); body = (0, Serializer_1.serializeMethodResponse)(allResponses); } } else { const res = await this._methodCallHandler(methodName, args, req); body = res instanceof XmlRpcFault_1.XmlRpcFault ? (0, Serializer_1.serializeFault)(res) : (0, Serializer_1.serializeMethodResponse)(res); } const contentLength = String(new TextEncoder().encode(body).length); return { statusCode: 200, headers: { "Content-Type": "text/xml", "Content-Length": contentLength }, body, }; }; this._methodCallHandler = async (methodName, args, req) => { const handler = this.xmlRpcHandlers.get(methodName); if (handler == undefined) { return new XmlRpcFault_1.XmlRpcFault(`Method "${methodName}" not found`, Serializer_1.XmlRpcError.NOT_FOUND_ERROR); } try { const res = await handler(methodName, args, req); return res; } catch (err) { return err instanceof XmlRpcFault_1.XmlRpcFault ? err : new XmlRpcFault_1.XmlRpcFault(String(err.stack ?? err)); } }; this.server = server; server.handler = this._requestHandler; // Our HTTP handler } url() { return this.server.url(); } port() { return this.server.port(); } async listen(port, hostname, backlog) { await this.server.listen(port, hostname, backlog); } close() { this.server.close(); } setHandler(methodName, handler) { this.xmlRpcHandlers.set(methodName, handler); } } exports.XmlRpcServer = XmlRpcServer; //# sourceMappingURL=XmlRpcServer.js.map