import { SurveyRunner } from "./SurveyRunner"; export interface MicrosurveyClientOptions { env?: "development" | "production" | "test"; apiUrl?: string; debug?: boolean; projectId?: string; identity?: string; surveys?: []; } export class MicrosurveyClient { runners: SurveyRunner[] = []; constructor(private readonly options: MicrosurveyClientOptions) {} public async init(): Promise { const opts = this.options; const apiUrl = opts.apiUrl ?? "https://samelogic.com/api"; if (!opts.projectId) { if (opts.debug) console.log("samelogic: No project specified"); return; } // fetch surveys and wait for their triggers this.fetchProject(apiUrl, opts.projectId); } private async fetchProject( apiUrl: string, projectId: string // surveys?: string[] ) { const params = new URLSearchParams(); params.set("projectId", projectId); // if (surveys) params.set("surveys", surveys); try { const res = await fetch(`${apiUrl}/projects?${params}`); const data = await res.json(); for (let research of data.researches) { const form = research.form; const runner = new SurveyRunner(research.researchId, form); runner.setIdentity(this.options.identity); // store runner this.runners.push(runner); } // setup microsurveys one by one } catch (e) { console.error("Samelogic: Error loading microsurveys"); console.error(e); } } public async setIdentity(identity?: string) { for (let runner of this.runners) { runner.setIdentity(identity); } } public static async init( options?: MicrosurveyClientOptions ): Promise { const client = new MicrosurveyClient(options || {}); await client.init(); return client; } }