// common.ts - common stuff like config and app setup import { createApp } from 'petite-vue' import { Data } from './comp-data' import { domain, nopoll } from '@params' type Config = { apiurl: string pollurl: string domain: string itemid: string sid: string iid: string nopoll: boolean } export function config (api, polling): Config { const pu = polling ? `${api.path}/${polling.msgbase.join('/')}` : '' const urlparams = new URL(location.href).searchParams return { apiurl: api.path, pollurl: pu, domain: domain, itemid: urlparams.get('id'), sid: getSid(), iid: createRandString(1), nopoll: nopoll } } export const pvapp = { run(conf: Config) { appdata.conf = conf if (appdata.conf.pollurl && !appdata.conf.nopoll) { appdata.poll() } createApp(appdata).mount() } } const appdata = { $delimiters: ['{|', '|}'], conf: {} as Config, components: {}, output: '', // debug output space handle, poll, Data } // App (appdata) methods function handle(msg) { const data = JSON.parse(msg.payload) const [ domain, action, class_, item ] = msg.path.split('/') // TODO: check action => select handler fct const comp = this.components[class_ || 'data'] if (domain && domain != comp.domain) { return } if (comp) { comp.handle(domain, action, class_, item, data) } } function poll() { dopoll(this) } // basic functions - move to api.ts export async function sendMsg(conf: Config, basemsg: string[], data: any) { const url = `${conf.apiurl}/${basemsg.join('/')}` await send(url, conf, data) } async function send(url: string, conf: Config, data: any) { data._interaction = conf.iid const body = JSON.stringify(data) const headers = {} headers['X-Integrator-Session'] = conf.sid return fetch(url, { method: 'POST', headers: headers, body: body }) } function createRandString(size: number): string { const arr = new Uint32Array(size) crypto.getRandomValues(arr) const result: string[] = [] arr.forEach((x) => result.push(x.toString(36))) return result.join('') } function getSid(): string { const sid_key = 'api.sessionid' let sid = localStorage.getItem(sid_key) if (!sid) { sid = createRandString(2) localStorage.setItem(sid_key, sid) } return sid } //console.log("sid: ", getSid()) // TODO: clear sid - when? //localStorage.setItem('api.sessionid', '') async function dopoll(app: typeof appdata) { const wait_time = 10000 while (true) { try { const res = await(send(app.conf.pollurl, app.conf, {})) const msg = await res.json() console.log(msg) switch (msg.status) { case 'idle': break case 'data': app.handle(msg) break default: console.log('poll response: ', msg) await sleep(wait_time) } } catch (error) { console.log(error) await sleep(wait_time) } } } const sleep = (delay: number) => new Promise(r => setTimeout(r, delay))