UNPKG

@fuwu-yuan/bgew

Version:

Baguette Game Engine Web is a french 2D Web game engine

81 lines (80 loc) 2.57 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AbstractNetworkManager = void 0; const axios_1 = __importDefault(require("axios")); /** * A network manager is aim to manage communication with your server API and websocket server */ class AbstractNetworkManager { constructor(board) { this.webSocketSubject = null; this.msgsPromises = []; this.board = board; this.api = axios_1.default.create(); this.checkPageReload(); this.init(); } init() { this.api = axios_1.default.create({ baseURL: this.apiUrl, timeout: 1000, headers: { 'Accept': 'application/json', 'rejectUnauthorized': 'false', } }); console.log("Networkmanager ready :"); console.log("• API URL: " + this.apiUrl); } /** * Disconnect from websocket */ leaveRoom() { if (this.webSocketSubject) { this.webSocketSubject.unsubscribe(); } } /** * Open a room (similar to closeRoom(uid, false) * @param uid */ openRoom(uid) { return this.closeRoom(uid, false); } sendMessage(message) { var _a; let timestamp = (new Date()).getTime(); let promise = new Promise((resolve, reject) => { this.msgsPromises.push({ timestamp: timestamp, promise: { resolve: resolve, reject: reject } }); }); (_a = this.webSocketSubject) === null || _a === void 0 ? void 0 : _a.next({ id: timestamp, msg: message }); return promise; } msgSentConfirmation(message) { let index = this.msgsPromises.findIndex((msgPromiseExec) => { return msgPromiseExec.timestamp === message.data.msg.id; }); if (index > -1) { let promise = this.msgsPromises[index]; promise.promise.resolve(message); this.msgsPromises.splice(index, 1); } } /** * This function check if page is reloaded and disconnect the socket * * @private */ checkPageReload() { window.addEventListener("unload", (event) => { console.log("The page is refreshing"); if (this.webSocketSubject) { this.webSocketSubject.unsubscribe(); } }); } } exports.AbstractNetworkManager = AbstractNetworkManager;