UNPKG

ziplyne-dap-sdk

Version:

Ziplyne DAP SDK - Pure JavaScript Analytics SDK for React Native (Expo compatible)

87 lines (73 loc) 2.29 kB
// Pure JavaScript implementation - no native modules needed class ZiplyneDAP { constructor() { this.isInitialized = false; this.apiKey = null; this.baseURL = "http://localhost:4000/api/v2/mobileanalytics/beacon"; } /** * Initialize the SDK with company API key * @param {string} apiKey - Company API key for identifying events */ init(apiKey) { if (!apiKey || typeof apiKey !== 'string') { throw new Error('ZiplyneDAP.init() requires a valid API key string'); } if (this.isInitialized) { console.warn('ZiplyneDAP already initialized. Ignoring duplicate init call.'); return; } this.apiKey = apiKey; this.isInitialized = true; } /** * Track an event with optional properties * @param {string} eventName - Name of the event to track * @param {Object} properties - Optional properties object * @returns {Promise<boolean>} - Promise that resolves to true on success */ async track(eventName, properties = {}) { if (!this.isInitialized) { throw new Error('ZiplyneDAP not initialized. Call ZiplyneDAP.init() first.'); } if (!eventName || typeof eventName !== 'string') { throw new Error('ZiplyneDAP.track() requires a valid event name string'); } if (properties && typeof properties !== 'object') { throw new Error('ZiplyneDAP.track() properties must be an object'); } try { return await this._sendEventToServer(eventName, properties); } catch (error) { console.error('ZiplyneDAP: Failed to track event:', error.message); throw error; } } /** * Send event data to server * @private */ async _sendEventToServer(eventName, properties) { const eventPayload = { event_name: eventName, properties: { ...properties, timestamp: new Date().toISOString() } }; const response = await fetch(this.baseURL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': this.apiKey }, body: JSON.stringify(eventPayload), }); if (!response.ok) { throw new Error(`Server returned status code ${response.status}`); } return true; } } // Export singleton instance module.exports = new ZiplyneDAP();