node-httpx-server
Version:
A node HTTP/2 server and beyond dealing with streams
59 lines • 2.14 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpxServer = void 0;
const http2_1 = require("http2");
const helpers_1 = require("./helpers");
class HttpxServer {
constructor({ server, onComplete = ({ stream, message }) => {
stream.end(message);
}, onError = ({ error, stream }) => {
stream.end(error.message);
}, onPreServe, port = 8080, hostname = 'localhost', }) {
this.serve = () => {
this.server.on('stream', (stream, headers, flags) => {
const source = { stream, headers, flags };
if (!this.onPreServe) {
this.startServe({ source });
return;
}
this.onPreServe({
error: (err) => this.error({ error: err, stream }),
next: () => this.startServe({ source }),
source,
});
});
this.server.listen(this.port, this.hostname, () => {
console.info(`Server running on ${this.hostname}:${this.port}`);
});
};
this.startServe = ({ source }) => {
const headerPath = source.headers[http2_1.constants.HTTP2_HEADER_PATH];
if (!headerPath) {
this.error({
error: new Error(':path missing'),
stream: source.stream,
});
return;
}
(0, helpers_1.processRoutes)({
currentPath: headerPath,
onComplete: this.complete,
onError: this.error,
routers: this.routers,
source,
});
};
this.router = (path, ...callbacks) => {
this.routers.set([path], callbacks);
};
this.server = server;
this.routers = new Map();
this.complete = onComplete;
this.error = onError;
this.onPreServe = onPreServe;
this.port = port;
this.hostname = hostname;
}
}
exports.HttpxServer = HttpxServer;
//# sourceMappingURL=httpxServer.js.map