sql-snap
Version:
Tools for running SQL Database Tests
52 lines (51 loc) • 1.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const ws_1 = require("ws");
const snap_1 = require("./snap");
class SnapServer {
constructor(config) {
this.server = new ws_1.Server({
port: config.port
});
this.snap = new snap_1.Snap(config.dbConfig);
this.snap.connect()
.then(() => {
console.log("Ready");
this.server.on('connection', this.newSocket.bind(this));
}).catch((error) => {
console.log("Failed to connect");
console.error(error);
});
}
newSocket(ws, request) {
ws.on('message', this.onMessage.bind({ snap: this.snap, ws }));
}
onMessage(raw) {
const message = JSON.parse(raw);
if (message.type === 'query') {
this.snap.query(message.data)
.then((result) => {
this.ws.send(JSON.stringify({
type: 'response',
data: result,
id: message.id
}));
})
.catch((error) => {
this.ws.send(JSON.stringify({
type: 'error',
data: error,
id: message.id
}));
});
}
else {
this.ws.send(JSON.stringify({
type: 'error',
data: new Error("Incorrect Message Type"),
id: message.id
}));
}
}
}
exports.SnapServer = SnapServer;