-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
138 lines (130 loc) · 4.53 KB
/
Copy pathclient.js
File metadata and controls
138 lines (130 loc) · 4.53 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
const env = process.env.NODE_ENV || "dev"
const isFunction = require("lodash/isFunction")
const get = require("lodash/get")
const each = require("lodash/each")
const { Obs, observable, observeSync } = require("kobs")
const unwatchDelay = 1000 * 60 * 2 // server unwatch is called if UI is not observing during 2 minutes
const invalidQuery = new Error("invalid-query")
const validateQuery = (q) => {
if (!q) throw invalidQuery
if (typeof q === "string") return
if (Array.isArray(q)) {
q.forEach(validateQuery)
return
}
if (typeof q === "object") {
if (!Object.keys(q).length) throw invalidQuery
each(q, (v) => {
if (v === undefined) throw invalidQuery
})
return
}
throw invalidQuery
}
const startWatching = (rawClient, watchId, method, arg, obs, suffix) => {
const watchMethod = suffix ? "watch2" : "watch"
rawClient[watchMethod]({ watchId, method, arg }, (value) => {
if (value !== get(obs, "value.value")) {
// évite de déclencher si la valeur reste identique (normalement c'est déjà filtré par le serveur mais c'est utile à la reconnection)
obs.set({ loaded: true, value })
}
}).catch((err) => {
console.error("Error starting to watch", arg, err)
})
}
const createWatch = (rawClientObs, suffix) => {
const queriesCache = new Map()
const pendingUnwatch = new Map()
// relaunch watched queries for each new rawClient
observeSync(rawClientObs, (rawClient) => {
if (!rawClient) return
queriesCache.forEach((obs, watchId) => {
const { method, arg } = JSON.parse(watchId)
startWatching(rawClient, watchId, method, arg, obs, suffix)
})
})
const watch = (method, arg) => {
const watchId = JSON.stringify({ method, arg })
let obs = queriesCache.get(watchId)
const cancelPendingUnwatch = pendingUnwatch.get(watchId)
if (cancelPendingUnwatch) {
clearTimeout(cancelPendingUnwatch)
}
if (!obs) {
const unwatch = () => {
const rawClient = rawClientObs()
if (!rawClient.closed) {
//si la connection est tombée, ça ne sert à rien de demander un désabonnement (normalement le serveur l'a déjà fait de son côté)
const unwatchFn = rawClient[suffix ? "unwatch2" : "unwatch"]
unwatchFn({ watchId }).catch((err) => {
console.error("Error stopping to watch", method, arg, err)
})
}
queriesCache.delete(watchId)
pendingUnwatch.delete(watchId)
//console.log("unwatched query", q)
}
const onUnobserved = () => {
pendingUnwatch.set(watchId, setTimeout(unwatch, unwatchDelay))
//console.log("query scheduled to be unwatched", q)
}
obs = new Obs(
{ loaded: false, value: undefined },
onUnobserved,
null,
watchId
)
queriesCache.set(watchId, obs)
// start watching server
if (env === "dev" && method === "query") {
validateQuery(arg)
}
startWatching(rawClientObs(), watchId, method, arg, obs, suffix)
}
return obs.get()
}
return watch
}
module.exports = (rawClientArg, authenticatedUser) => {
const rawClientObs = observable()
if (isFunction(rawClientArg)) {
// rawClientArg is a function that pulses when a new rawClient should be used
rawClientArg((newClient) => {
const rawClient = rawClientObs()
rawClient && rawClient.close && rawClient.close() //normalement rawClient est déconnecté mais par sécurité
console.log("new raw client ", newClient.timestamp)
rawClientObs(newClient)
})
} else {
// if not a function, then it's a static raw-client
rawClientObs(rawClientArg)
}
const onDisconnect = (cb) =>
observeSync(
rawClientObs,
(rawClient) => rawClient && rawClient.onDisconnect(cb)
)
const watch = createWatch(rawClientObs)
const watch2 = createWatch(rawClientObs, "2")
const proxyRawMethod = (method) =>
function () {
const rawClient = rawClientObs()
return rawClient[method].apply(rawClient, arguments)
}
return {
authenticatedUser,
call: proxyRawMethod("call"),
watch,
watch2,
clearLocalData: () => rawClientObs().call("clearLocalData"),
loadBackup: (data) => rawClientObs().call("loadBackup", data),
close: proxyRawMethod("close"),
onDisconnect,
query: (q) => watch("query", q),
query2: (q) => watch2("query", q),
queryOnce: proxyRawMethod("query"),
queryOnce2: proxyRawMethod("query2"),
patch: proxyRawMethod("patch"),
modelCall: (modelPath, arg) => watch("modelCall", { modelPath, arg }),
}
}