71 lines
1.6 KiB
TypeScript
71 lines
1.6 KiB
TypeScript
// common.ts - common stuff like config and app setup
|
|
|
|
import { domain } from '@params'
|
|
|
|
export type Config = {
|
|
domain: string
|
|
itemid: string
|
|
sid: string
|
|
iid: string
|
|
apiurl: string
|
|
pollurl: string
|
|
}
|
|
|
|
export function config (api): Config {
|
|
const pu = api.polling ? `${api.path}/${api.polling.msgbase.join('/')}` : ''
|
|
const urlparams = new URL(location.href).searchParams
|
|
return {
|
|
domain: domain,
|
|
//itemid: location.hash.substring(1),
|
|
itemid: urlparams.get('id'),
|
|
sid: getSid(),
|
|
iid: createRandString(1),
|
|
apiurl: api.path,
|
|
pollurl: pu,
|
|
}
|
|
}
|
|
|
|
// generic App (appdata) methods
|
|
|
|
export function register(name: string, comp: any) {
|
|
this.components[name] = comp
|
|
comp.initialize()
|
|
}
|
|
|
|
// common functions
|
|
|
|
export function handle(app, msg) {
|
|
const [ domain, action, class_, item ] = msg.path.split('/')
|
|
const comp = app.components[class_ || 'data']
|
|
if (!comp) {
|
|
msg.log(`**** handle: component ${class_} not found.`)
|
|
}
|
|
if (domain && domain !== comp.domain) {
|
|
return
|
|
}
|
|
comp.handle(domain, action, class_, item, msg.payload)
|
|
}
|
|
|
|
export 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', '')
|
|
|
|
export const sleep = (delay: number) => new Promise(r => setTimeout(r, delay))
|