UNPKG

@adizen/events-hub-sdk

Version:

Official client SDK for triggering Events Hub workflows from any app

93 lines (92 loc) 2.37 kB
// src/index.ts import axios from "axios"; var DEFAULT_TIMEOUT_MS = 1e4; var EventsHubClient = class { constructor(config) { if (!config?.baseUrl) { throw new Error("EventsHubClient requires a baseUrl"); } const baseURL = config.baseUrl.replace(/\/+$/, ""); this.apiKey = config.apiKey; this.apiKeyHeader = config.apiKeyHeader ?? "x-api-key"; this.defaultHeaders = config.defaultHeaders ?? {}; this.http = axios.create({ baseURL, timeout: config.timeoutMs ?? DEFAULT_TIMEOUT_MS }); } /** * Trigger a single event immediately (or with optional delay/schedule). */ async trigger(eventName, data, options) { const payload = { name: eventName, data, userId: options?.userId, metadata: options?.metadata, delay: options?.delay, schedule: options?.schedule }; const response = await this.http.post( "/api/events", payload, this.buildRequestConfig() ); return response.data; } /** * Trigger multiple events in a single request. */ async triggerBatch(events) { const response = await this.http.post( "/api/events/batch", events, this.buildRequestConfig() ); return response.data; } /** * Convenience helper to trigger an event after a delay (ms). */ async triggerDelayed(eventName, data, delayMs, options) { return this.trigger(eventName, data, { ...options, delay: delayMs }); } /** * Convenience helper to schedule an event using a cron expression. */ async triggerScheduled(eventName, data, cronExpression, options) { return this.trigger(eventName, data, { ...options, schedule: cronExpression }); } /** * Retrieve handler metadata (useful for schema introspection in apps). */ async getHandler(handlerId) { const response = await this.http.get( `/api/admin/handlers/${handlerId}`, this.buildRequestConfig() ); return response.data; } /** * Private helper to build HTTP headers. */ buildRequestConfig(overrides) { const headers = { ...this.defaultHeaders, ...overrides?.headers }; if (this.apiKey && !headers[this.apiKeyHeader]) { headers[this.apiKeyHeader] = this.apiKey; } return { ...overrides, headers }; } }; export { EventsHubClient };