UNPKG

swipelime-client-node

Version:

swipelime-client-node is the official swipelime Node.js client library

175 lines (174 loc) 6.93 kB
"use strict"; // Copyright (c) 2024 swipelime (https://swipelime.com) // Use of this source code is governed by an MIT // license that can be found in the LICENSE file. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Client = exports.ServiceHandler = exports.TaskCommand = exports.TaskEvent = void 0; const events_1 = require("events"); const simpleddp_node_1 = __importDefault(require("simpleddp-node")); const ws_1 = __importDefault(require("ws")); const ServiceHandler_1 = require("./ServiceHandler"); Object.defineProperty(exports, "ServiceHandler", { enumerable: true, get: function () { return ServiceHandler_1.ServiceHandler; } }); const TaskEvent_1 = __importDefault(require("./models/TaskEvent")); exports.TaskEvent = TaskEvent_1.default; const TaskCommand_1 = __importDefault(require("./models/TaskCommand")); exports.TaskCommand = TaskCommand_1.default; const utils_1 = require("./utils"); __exportStar(require("./types"), exports); class Client { _authParams; _ddpClient; _eventEmitter; _isInitialized = false; _isLoggedIn = false; _isConnected = false; _serviceHandlers = []; apiVersion = 1; clientVersion = '0.4.2'; get isLoggedIn() { return this._isLoggedIn; } get isConnected() { return this._isConnected; } get emitter() { return this._eventEmitter; } constructor(authParams, options) { if (!authParams.username) { throw (0, utils_1.swipelimeError)('Username is required'); } if (!authParams.password) { throw (0, utils_1.swipelimeError)('Username is required'); } this._eventEmitter = new events_1.EventEmitter(); this._eventEmitter.setMaxListeners(100); this._authParams = authParams; const ddpOptions = { endpoint: (0, utils_1.getServerUrlForEnvironment)(options?.environment), SocketConstructor: ws_1.default, reconnectInterval: options?.reconnectInterval ?? 5000 }; this._ddpClient = new simpleddp_node_1.default(ddpOptions); this.init(); } init() { if (this._isInitialized) return; this._isInitialized = true; this._ddpClient.on('connected', async () => { this._isConnected = true; if (!(await this._ddpClient.call(`api/v${this.apiVersion}/isVersionValid`, this.clientVersion))) { this._eventEmitter.emit('error', (0, utils_1.swipelimeConsoleError)('Client version is not supported')); this._ddpClient.disconnect(); return; } this._eventEmitter.emit('connected'); try { const loginResult = await this._ddpClient.login({ password: this._authParams.password, user: { username: this._authParams.username } }); if (!loginResult) { this._eventEmitter.emit('error', (0, utils_1.swipelimeConsoleError)('Failed to login')); this._ddpClient.disconnect(); } } catch (e) { const meteorError = e; this._eventEmitter.emit('error', (0, utils_1.swipelimeConsoleError)(meteorError.message)); } }); this._ddpClient.on('login', (user) => { this._isLoggedIn = true; this._eventEmitter.emit('login', user); }); this._ddpClient.on('logout', () => { this._isLoggedIn = false; this._eventEmitter.emit('logout'); }); this._ddpClient.on('disconnected', () => { this._isConnected = false; this._isLoggedIn = false; this._eventEmitter.emit('disconnected'); }); this._ddpClient.on('error', (e) => { this._eventEmitter.emit('error', (0, utils_1.swipelimeConsoleError)(e.msg)); }); } // Low level method to call a method on the server // This method will catch any errors and emit an 'error' event // Returns undefined if an error occurs callMethod = async (method, ...args) => { try { return await this._ddpClient.call(method, ...args); } catch (error) { if (error.errorType === 'Meteor.Error') { this.emitter.emit('error', (0, utils_1.swipelimeConsoleError)(`Error calling method ${method}: ${error.message}${error.details ? ` ${error.details}` : ''}`)); } else { this.emitter.emit('error', (0, utils_1.swipelimeConsoleError)(`Error calling method ${method}: ${JSON.stringify(error)}`)); } return undefined; } }; /** * Pings the server which will return 'pong' */ async ping() { return this.callMethod(`api/v${this.apiVersion}/methods/ping`); } /** * Returns the latency in milliseconds */ async getLatency() { const started = new Date().getTime(); await this.ping(); const ended = new Date().getTime(); return ended - started; } /** * Returns an array of available tenant IDs that the client can access */ async getAvailableTenantIds() { return this.callMethod(`api/v${this.apiVersion}/getAvailableTenants`); } /** * Adds a service handler for the specified tenant ID * Service handlers are used to interact with the API for a specific tenant */ async addServiceHandler({ tenantId }) { if (!tenantId) { throw (0, utils_1.swipelimeError)('Tenant ID is required'); } if (!this._isLoggedIn) await (0, events_1.once)(this._eventEmitter, 'login'); const serviceHandler = new ServiceHandler_1.ServiceHandler(this, this._ddpClient, tenantId); this._serviceHandlers.push(serviceHandler); return serviceHandler; } getServiceHandlers() { return this._serviceHandlers; } } exports.Client = Client;