aboutsummaryrefslogtreecommitdiffstats
path: root/web/src/js/backends/static.js
blob: 676468ce5c8804c0d14f5386d40f2ef42f1bcdf6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * This backend uses the REST API only to host static instances,
 * without any Websocket connection.
 */
import { fetchApi } from "../utils"

const CMD_RESET = 'reset'

export default class StaticBackend {
   constructor(store) {
       this.activeFetches = {}
       this.store = store
       this.onOpen()
   }

   onOpen() {
        this.fetchData("settings")
        this.fetchData("flows")
        this.fetchData("events")
        this.fetchData("options")
   }

   fetchData(resource) {
       let queue = []
       this.activeFetches[resource] = queue
       fetchApi(`/${resource}`)
           .then(res => res.json())
           .then(json => {
               if (this.activeFetches[resource] === queue)
                   this.receive(resource, json)
           })
   }

   onMessage(msg) {
       if (msg.cmd === CMD_RESET) {
           return this.fetchData(msg.resource)
       }
       if (msg.resource in this.activeFetches) {
           this.activeFetches[msg.resource].push(msg)
       } else {
           let type = `${msg.resource}_${msg.cmd}`.toUpperCase()
           this.store.dispatch({ type, ...msg})
       }
   }

   receive(resource, data) {
       let type = `${resource}_RECEIVE`.toUpperCase()
       this.store.dispatch({ type, cmd: "receive", resource, data })
       let queue = this.activeFetches[resource]
       delete this.activeFetches[resource]
       queue.forEach(msg => this.onMessage(msg))
   }

}