bagman
Version:
js/ts client for Bagman
92 lines (91 loc) • 4.08 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bagman = void 0;
const socket_io_client_1 = require("socket.io-client");
const channel_1 = require("./channel");
const security_context_1 = require("./security-context");
const GLOBAL_EVENT = ["connect", "connect_error", "disconnect", "disconnecting"];
class Bagman {
/**
* Creates a new `Bagman` instance.
* @param {BagmanArgs} - The URL for the websocket server.
*/
constructor(config) {
this.config = config;
this.securityCtx = new security_context_1.SecurityContext(config);
this.socket = (0, socket_io_client_1.io)(this.config.url || "http://localhost:8080", {
transports: ["websocket"],
autoConnect: false,
});
// connect to bagman server if authorized
if (this.securityCtx.isAuthorized()) {
this.socket.auth = {
'apiKey': this.securityCtx.token()
};
this.socket.connect();
}
}
authorize() {
return __awaiter(this, void 0, void 0, function* () {
yield this.securityCtx.authorize();
// connect to bagman server with token
if (this.securityCtx.isAuthorized()) {
// add api key headers to client
// after authorisation
this.socket.auth = {
'apiKey': this.securityCtx.token()
};
this.socket.connect();
}
});
}
/**
* Subscribes to a channel.
* @async
* @param {string} channel - The name of the channel to subscribe to.
* @param {object} [options] - Optional parameters for the subscription.
* @param {boolean} [options.withPresence=false] - Whether to subscribe to the channel with presence functionality.
* @throws {Error} Throws an error if the client is not authorized.
* @throws {Error} Throws an error if the subscription fails.
* @returns {Promise<Channel>} A Promise that resolves with a Channel instance representing the subscribed channel.
*/
subscribe(channel, { withPresence } = { withPresence: false }) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.securityCtx.isAuthorized())
throw new Error("Unauthorized. Please authorize client and proceed again.");
const ack = yield this.socket.emitWithAck('client:subscribe', { channel, withPresence });
if (ack.status === "error") {
throw new Error(ack.message);
}
return new channel_1.Channel(this.socket, channel);
});
}
/**
* Listens to a specific global event.
* @template T The type of the arguments to be passed to the callback.
* @param {GlobalEvent} event - The global event to listen to.
* @param {(...args: T) => Promise<void> | void} cb - The callback to be called when the event is emitted.
* @throws {Error} When an invalid event is provided.
*/
listen(event, cb) {
if (!GLOBAL_EVENT.includes(event))
throw new Error(`Invalid Global event: ${event}`);
this.socket.on(event, cb);
}
close() {
// defensive on not connected socket
if (this.socket.connected) {
this.socket.disconnect();
}
}
}
exports.Bagman = Bagman;