@x5e/gink
Version:
an eventually consistent database
76 lines • 3.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleServer = void 0;
const Database_1 = require("./Database");
const typedefs_1 = require("./typedefs");
const Listener_1 = require("./Listener");
const utils_1 = require("./utils");
const ServerConnection_1 = require("./ServerConnection");
/**
* A server that connects all inbound websocket connections to a single database instance.
*/
class SimpleServer extends Database_1.Database {
constructor(args) {
super(args);
this.listener = new Listener_1.Listener({
requestHandler: this.onRequest.bind(this),
requestListener: this.requestListener.bind(this),
index: "/static/dashboard/dashboard.html",
...args,
});
this.authFunc = args.authFunc || (() => true);
this.ready = Promise.all([this.ready, this.listener.ready]).then(() => args.logger(`SimpleServer.ready`));
}
async onRequest(request) {
await this.ready;
let protocol = null;
let token = null;
if (request.requestedProtocols.length) {
for (const protocol of request.requestedProtocols) {
if (protocol.match(/0x.*/)) {
token = (0, utils_1.decodeToken)(protocol);
}
}
if (request.requestedProtocols.includes(typedefs_1.PROTOCOL))
protocol = typedefs_1.PROTOCOL;
else
return request.reject(400, "bad protocol");
}
if (!this.authFunc(token)) {
return request.reject(401, "authentication failed");
}
const websocketConnection = request.accept(protocol, request.origin);
this.logger(`Connection accepted from ${request.remoteAddress}`);
const connection = new ServerConnection_1.ServerConnection({
onClose: () => {
this.connections.delete(connectionId);
this.logger(`connection ${connectionId} closed`);
},
onData: (data) => this.receiveMessage(data, connectionId),
websocketConnection,
});
const connectionId = this.createConnectionId();
this.connections.set(connectionId, connection);
connection.send(this.iHave.getGreetingMessageBytes());
connection.markHasSentGreeting();
}
requestListener(request, response) {
if (request.url.startsWith("/api/connections")) {
if (request.method === "GET") {
let connections = Object.fromEntries(this.connections);
response.end(JSON.stringify(connections));
}
if (request.method === "POST") {
request.addListener("data", async (chunk) => {
response.statusCode = 400;
response.end(JSON.stringify(chunk));
});
}
}
else {
this.listener.requestListener(request, response);
}
}
}
exports.SimpleServer = SimpleServer;
//# sourceMappingURL=SimpleServer.js.map