@ably/cli
Version:
Ably CLI for Pub/Sub, Chat and Spaces
53 lines (52 loc) • 2.11 kB
JavaScript
import { AblyBaseCommand } from "./base-command.js";
import isTestMode from "./utils/test-mode.js";
// Dynamic import to handle module structure issues
let SpacesConstructor = null;
async function getSpacesConstructor() {
if (!SpacesConstructor) {
const spacesModule = (await import("@ably/spaces"));
const moduleAsRecord = spacesModule;
const defaultProperty = moduleAsRecord.default;
SpacesConstructor = (defaultProperty?.default ||
moduleAsRecord.default ||
moduleAsRecord);
}
return SpacesConstructor;
}
export class SpacesBaseCommand extends AblyBaseCommand {
// Ensure we have the spaces client and its related authentication resources
async setupSpacesClient(flags, spaceName) {
// First create an Ably client
const realtimeClient = await this.createAblyRealtimeClient(flags);
if (!realtimeClient) {
this.error("Failed to create Ably client");
}
// Create a Spaces client using the Ably client
const spacesClient = await this.createSpacesClient(realtimeClient);
// We set the offline timeout to 2s otherwise Spaces will hang on to left members for 2 minutes.
const options = {
offlineTimeout: 2000,
};
// Get a space instance with the provided name
const space = await spacesClient.get(spaceName, options);
return {
realtimeClient,
space,
spacesClient,
};
}
async createSpacesClient(realtimeClient) {
// If in test mode, skip connection and use mock
if (isTestMode()) {
this.debug(`Running in test mode, using mock Ably Spaces client`);
const mockAblySpaces = this.getMockAblySpaces();
if (mockAblySpaces) {
// Return mock as appropriate type
return mockAblySpaces;
}
this.error(`No mock Ably Spaces client available in test mode`);
}
const Spaces = await getSpacesConstructor();
return new Spaces(realtimeClient);
}
}