import { InitParameters, SendEventParameters } from './types' const generateError = (message: string) => `Relay SDK: ${message}` const SDK = class { fetch: typeof window.fetch apiURL = 'https://relay-plantkit.vercel.app/api/' apiKey = '' id = '' constructor(_fetch: any, id: string) { if (_fetch) { this.fetch = _fetch } this.id = id if (!this.fetch && typeof fetch === 'undefined') { console.error('Fetch function is undefined') } if (!this.id) { console.error('ID is undefined') } } init = (data: InitParameters) => { if (data.fetch) { this.fetch = data.fetch } if (data.apiURL) { this.apiURL = data.apiURL if (!this.apiURL.endsWith('/')) { this.apiURL += '/' } } if (data.apiKey) { this.apiKey = data.apiKey } } sendEvent = async ( data: { //Common properties that will be filterable event?: string rating?: number sessionId?: string sku?: string total?: number userId?: string isTest?: boolean //Additional generic properties that are indexed propertyNumber1?: number propertyNumber2?: number propertyNumber3?: number lat?: number lng?: number propertyString1?: string source?: string propertyString2?: string propertyString3?: string } & Record, params?: Omit & { tags?: string[] apiKey?: string }, ) => { const { tags, ...rest } = params if (rest?.apiKey) { this.init({ ...rest, apiKey: rest.apiKey }) } this._validateSendEvent(data) const body = JSON.stringify({ data, tags: (tags || []).concat([this.id]), }) return (this.fetch || fetch)(`${this.apiURL}submissions/`, { body, headers: { 'Content-Type': 'application/json', 'X-API-Key': this.apiKey, }, method: 'POST', }).then((res) => res.json()) } _validateSendEvent(data: SendEventParameters) { if (!data) { throw new Error(generateError('Attempting to send null data')) } if (!this.apiKey) { throw new Error( generateError( 'Attempting to send data with no API key, make sure you set it in sendEvent or init', ), ) } if (!this.fetch && typeof fetch === 'undefined') { throw new Error( generateError( 'Attempting to send data with no API key, make sure you set it in sendEvent or init', ), ) } } } export default function getSDKInstance(fetch: any, id: string) { return new SDK(fetch, id) }