UNPKG

@smartsamurai/krapi-sdk

Version:

KRAPI TypeScript SDK - Easy-to-use client SDK for connecting to self-hosted KRAPI servers (like Appwrite SDK)

118 lines (101 loc) 2.87 kB
/** * Connection Manager * * Handles client/server mode detection, endpoint validation, and service initialization. */ import { Logger } from "../core"; import { KrapiError } from "../core/krapi-error"; import { KrapiConfig } from "../krapi"; import { normalizeEndpoint, validateEndpoint } from "../utils/endpoint-utils"; export type Mode = "client" | "server" | null; export class ConnectionManager { private mode: Mode = null; private config: KrapiConfig | null = null; private logger: Logger = console; private currentEndpoint: string | null = null; /** * Connect to KRAPI (client or server mode) */ async connect(config: KrapiConfig): Promise<void> { if ("endpoint" in config) { // Client mode const newEndpoint = config.endpoint; // Validate endpoint const validation = validateEndpoint(newEndpoint); if (!validation.valid) { throw KrapiError.validationError(`Invalid endpoint: ${validation.error}`, "endpoint"); } // Normalize endpoint const normalizedEndpoint = normalizeEndpoint(newEndpoint, { warnOnBackendPort: true, autoAppendPath: true, logger: console, }); // Detect reconnection const isReconnection = this.mode === "client" && this.currentEndpoint && this.currentEndpoint !== normalizedEndpoint; if (isReconnection) { this.logger.warn( `SDK reconnecting from ${this.currentEndpoint} to ${normalizedEndpoint}. ` + `All HTTP clients will be recreated with the new endpoint.` ); } this.config = { ...config, endpoint: normalizedEndpoint }; this.mode = "client"; this.logger = console; this.currentEndpoint = normalizedEndpoint; } else if ("database" in config) { // Server mode this.mode = "server"; this.currentEndpoint = null; this.logger = config.logger || console; this.config = config; } else { throw KrapiError.validationError( "Either endpoint (for client) or database (for server) must be provided", "config" ); } this.logger.info(`KRAPI SDK initialized in ${this.mode} mode`); } /** * Get current mode */ getMode(): Mode { return this.mode; } /** * Get current configuration */ getConfig(): KrapiConfig | null { return this.config; } /** * Get current endpoint (client mode only) */ getEndpoint(): string | null { return this.currentEndpoint; } /** * Get logger */ getLogger(): Logger { return this.logger; } /** * Check if connected */ isConnected(): boolean { return this.mode !== null && this.config !== null; } /** * Clear connection state */ clear(): void { this.mode = null; this.config = null; this.currentEndpoint = null; } }