@hrtk92/mcwsjs
Version:
  [](https://github.com/HRTK92/mcws.js/actions/workflows
130 lines (129 loc) • 4.06 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uuid_1 = require("uuid");
const ws_1 = require("ws");
class mswc {
constructor(host = 'localhost', port = 8000, debug = false) {
this.debug = false;
this.readyCallback = () => { };
this.connectionCallback = () => { };
this.dissconnectCallback = () => { };
this.eventCallbacks = {};
this.host = host;
this.port = port;
this.server = null;
this.ws = null;
this.debug = debug;
}
onReady(callback) {
this.readyCallback = callback;
}
onConnection(callback) {
this.connectionCallback = callback;
}
onDisconnect(callback) {
this.dissconnectCallback = callback;
}
on(eventName, callback) {
if (!this.eventCallbacks[eventName]) {
this.eventCallbacks[eventName] = [];
}
this.eventCallbacks[eventName].push(callback);
this.debug && console.log(`Added callback for ${eventName}`);
}
createServer() {
const wss = new ws_1.WebSocket.Server({ host: this.host, port: this.port });
this.server = wss;
wss.on('connection', (ws) => {
this.ws = ws;
this.connectionCallback(ws);
ws.on('message', (message) => {
const data = JSON.parse(message);
this.debug && console.log(data);
if (data.body.eventName) {
if (this.eventCallbacks[data.body.eventName]) {
this.debug && console.log(`Event ${data.body.eventName} triggered`);
this.eventCallbacks[data.body.eventName].forEach((callback) => {
callback(data);
});
}
}
});
});
wss.on('listening', () => {
this.readyCallback(this.host, this.port);
});
wss.on('close', () => {
this.dissconnectCallback();
});
}
disconnect() {
if (this.server) {
this.server.close();
}
else {
throw new Error('Server is not running');
}
}
subscribe(eventName) {
if (this.ws) {
this.ws.send(JSON.stringify({
body: {
eventName: eventName,
},
header: {
requestId: (0, uuid_1.v4)(),
messagePurpose: 'subscribe',
version: 1,
messageType: 'commandRequest',
},
}));
this.debug && console.log(`Subscribed to ${eventName}`);
}
else {
throw new Error('Server is not running');
}
}
unsubscribe(eventName) {
if (this.ws) {
this.ws.send(JSON.stringify({
body: {
eventName: eventName,
},
header: {
requestId: (0, uuid_1.v4)(),
messagePurpose: 'unsubscribe',
version: 1,
messageType: 'commandRequest',
},
}));
}
else {
throw new Error('Server is not running');
}
}
sendCommand(command) {
if (this.ws) {
this.ws.send(JSON.stringify({
header: {
requestId: (0, uuid_1.v4)(),
messagePurpose: 'commandRequest',
version: 1,
messageType: 'commandRequest',
},
body: {
origin: {
type: 'player',
},
commandLine: command,
version: 1,
},
}));
this.debug && console.log(`Sent command ${command}`);
}
else {
throw new Error('Server is not running');
}
}
}
exports.default = mswc;