@foxglove/xmlrpc
Version:
TypeScript library implementing an XMLRPC client and server with pluggable server backend
74 lines • 2.99 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpServerNodejs = void 0;
const http_1 = __importDefault(require("http"));
class HttpServerNodejs {
constructor() {
// eslint-disable-next-line @typescript-eslint/promise-function-async
this.handler = () => Promise.resolve({ statusCode: 404 });
this._server = new http_1.default.Server((req, res) => {
// Read the full request body into a string
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const body = Buffer.concat(chunks).toString();
// eslint-disable-next-line @typescript-eslint/no-misused-spread
const input = { ...req, body };
// Handle this request
this.handler(input)
.then((out) => {
// Write the HTTP response
res.shouldKeepAlive = out.shouldKeepAlive ?? res.shouldKeepAlive;
res.statusCode = out.statusCode;
res.statusMessage = out.statusMessage ?? "";
for (const [key, value] of Object.entries(out.headers ?? {})) {
res.setHeader(key, value);
}
res.end(out.body);
})
.catch((maybeErr) => {
const err = maybeErr;
const errStr = err.message;
// Write an HTTP error response
res.shouldKeepAlive = false;
res.statusCode = 500;
res.statusMessage = errStr;
res.end();
});
});
});
}
url() {
const addr = this._server.address();
if (addr == undefined || typeof addr === "string") {
return addr ?? undefined;
}
const hostname = addr.address === "::" ? "[::]" : addr.address;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
return `http://${hostname}${addr.port != undefined ? ":" + String(addr.port) : ""}/`;
}
port() {
const addr = this._server.address();
if (addr == undefined || typeof addr === "string") {
return undefined;
}
return addr.port;
}
async listen(port, hostname, backlog) {
await new Promise((resolve, reject) => {
this._server.on("error", reject);
this._server.listen(port, hostname, backlog, () => {
this._server.removeListener("error", reject);
resolve();
});
});
}
close() {
this._server.close();
}
}
exports.HttpServerNodejs = HttpServerNodejs;
//# sourceMappingURL=HttpServerNodejs.js.map