hugo-theme-cyberscopes/assets/js/app-ig.ts

71 lines
1.4 KiB
TypeScript

// app-ig.ts - petite-vue application using integrator API
import { createApp } from 'petite-vue'
import { Config, register, handle, sleep } from './common'
export const pvapp = {
run(conf: Config, components: any[]) {
appdata.conf = conf
for (const comp of components) {
appdata[comp.name] = comp
}
if (appdata.conf.pollurl) {
poll(appdata)
}
createApp(appdata).mount()
}
}
const appdata = {
$delimiters: ['{|', '|}'],
conf: {} as Config,
components: {},
register,
sendMsg
}
// methods
async function sendMsg(basemsg: string[], data: any) {
const url = `${this.conf.apiurl}/${basemsg.join('/')}`
await send(url, this.conf, data)
}
// functions
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
})
}
async function poll(app: typeof appdata) {
const wait_time = 10000
while (true) {
try {
const res = await(send(app.conf.pollurl, app.conf, {}))
const msg = await res.json()
switch (msg.status) {
case 'idle':
break
case 'data':
console.log('--- poll', msg)
handle(app, msg)
break
default:
console.log('**** poll', msg)
await sleep(wait_time)
}
} catch (error) {
console.log(error)
await sleep(wait_time)
}
}
}