UNPKG

@awhere/api

Version:

The awesome aWhere API for JavaScript.

57 lines 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Watcher = exports.WatchEvent = void 0; var uuid_1 = require("../utils/uuid"); var WatchEvent; (function (WatchEvent) { WatchEvent["change"] = "change"; WatchEvent["create"] = "create"; WatchEvent["update"] = "update"; WatchEvent["delete"] = "delete"; WatchEvent["restore"] = "restore"; WatchEvent["erase"] = "erase"; })(WatchEvent || (exports.WatchEvent = WatchEvent = {})); var Watcher = /** @class */ (function () { function Watcher(socket, namespace, itemId) { var _this = this; this.listEvents = {}; this.itemId = itemId; this.socket = socket; this.namepsace = namespace; this.generateId = uuid_1.uuid.createGenerator(this.namepsace); var evtId = this.generateId(); var fn = function () { return _this.socket.emit('call', "sub:".concat(namespace), itemId); }; this.listEvents[evtId] = { event: 'reconnect', fn: fn }; this.socket.on('reconnect', fn); } Watcher.prototype.on = function (event, callback) { var socketEvent = "".concat(this.namepsace, "/").concat(event); var evtId = this.generateId(); var fn = function (msg) { return callback(msg); }; this.listEvents[evtId] = { event: socketEvent, fn: fn }; this.socket.on(socketEvent, fn); }; Watcher.prototype.off = function (event) { var _this = this; var socketEvent = "".concat(this.namepsace, "/").concat(event); Object.keys(this.listEvents) .filter(function (key) { return _this.listEvents[key].event === socketEvent; }) .forEach(function (key) { var _a; _this.socket.off(_this.listEvents[key].event, (_a = _this.listEvents[key]) === null || _a === void 0 ? void 0 : _a.fn); delete _this.listEvents[key]; }); }; Watcher.prototype.unwatch = function () { var _this = this; this.socket.emit('call', "unsub:".concat(this.namepsace)); Object.keys(this.listEvents).forEach(function (key) { var _a; _this.socket.off(_this.listEvents[key].event, (_a = _this.listEvents[key]) === null || _a === void 0 ? void 0 : _a.fn); delete _this.listEvents[key]; }); }; return Watcher; }()); exports.Watcher = Watcher; //# sourceMappingURL=Watcher.js.map