-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.js
426 lines (392 loc) · 12.2 KB
/
service.js
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// import dateformat from 'dateformat'
import { ulid } from 'ulid'
import glue from './glue.js'
const uuidv4 = require('uuid/v4')
window.ULID = ulid
window.UUID = uuidv4
let host = ''
let wsOptions = {
// The base URL is appended to the host string. This value has to match with the server value.
baseURL: '',
// Force a socket type.
// Values: false, "WebSocket", "AjaxSocket"
forceSocketType: false,
// Kill the connect attempt after the timeout.
connectTimeout: 10000,
// If the connection is idle, ping the server to check if the connection is stil alive.
pingInterval: 35000,
// Reconnect if the server did not response with a pong within the timeout.
pingReconnectTimeout: 5000,
// Whenever to automatically reconnect if the connection was lost.
reconnect: true,
reconnectDelay: 1000,
reconnectDelayMax: 5000,
// To disable set to 0 (endless).
reconnectAttempts: 10,
// Reset the send buffer after the timeout.
resetSendBufferTimeout: 10000
}
// Create and connect to the server.
// Optional pass a host string and options.
let serviceGlobal // eslint-disable-line
class Event {
constructor () {
this.events = {}
}
on (eventName, fn) {
this.events[eventName] = this.events[eventName] || []
this.events[eventName].push(fn)
}
off (eventName, fn) {
if (this.events[eventName]) {
for (let i = 0; i < this.events[eventName].length; i++) {
if (this.events[eventName][i] === fn) {
this.events[eventName].splice(i, 1)
break
}
}
}
}
trigger (eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(function (fn) {
fn(data)
})
}
}
}
// store.state.auth.details.
export default class Service {
constructor (options) {
if (!options) options = {}
if (!options.env) options.env = {}
this.options = options
this.http = options.http
this.ws = options.ws
this.schemaURL = options.schemaURL || options.env.schemaURL || options.env.apiURL || `/api/v1/schema`
this.store = options.store
/* it is better to pass a preloaded schema in, otherwise we might hit a race condition
of the schema not being loaded before a service is called.
probably best to inject it serverside?
*/
this.schema = window.websiteSchema || options.schema
this.isReady = false
this.eventBus = new Event()
this.isUsingULIDAsPK = options.isUsingULIDAsPK || options.env.isUsingULIDAsPK || false
}
static create (options, context) {
serviceGlobal = new Service(options)
serviceGlobal.init()
console.log('opts', options)
return {
loading: true,
UUID: function () {
return uuidv4()
},
ULID: function () {
return ulid()
},
new: function (type, siteID) {
type = uppercaseFirst(type)
let record = serviceGlobal.construct(type)
if (Object.prototype.hasOwnProperty.call(record, 'UUID')) {
record.UUID = uuidv4()
} else if (Object.prototype.hasOwnProperty.call(record, 'ULID')) {
record.ULID = ulid()
} else if (Object.prototype.hasOwnProperty.call(record, `${type}ULID`)) {
record[`${type}ULID`] = ulid()
} else {
record.UniqueID = ulid()
}
checkSiteID(record, siteID, serviceGlobal.isUsingULIDAsPK)
return record
},
retrieve: function (type, recordID, ...qs) {
qs = makeQs(qs)
type = uppercaseFirst(type)
return serviceGlobal.retrieve(type, recordID, qs)
},
paged: function (type, sort, direction, limit, pageNum, ...qs) {
qs = makeQs(qs)
type = uppercaseFirst(type)
return serviceGlobal.paged(type, sort, direction, limit, pageNum, qs)
},
remove: function (type, recordID) {
type = uppercaseFirst(type)
if (typeof (recordID) === 'object') { // its actually the whole record
recordID = getIDField(type, recordID, serviceGlobal.isUsingULIDAsPK)
}
return serviceGlobal.remove(type, recordID)
},
send: function (msg) {
serviceGlobal.ws.send(msg)
},
subscribe: function (type, cb) {
type = uppercaseFirst(type)
serviceGlobal.subscribe(type, cb)
},
unsubscribe: function (type, cb) {
type = uppercaseFirst(type)
serviceGlobal.unsubscribe(type, cb)
},
save: function (type, record, ...qs) {
qs = makeQs(qs)
type = uppercaseFirst(type)
checkSiteID(record)
return serviceGlobal.save(type, record, qs)
}
}
}
static install (Vue, options) {
console.log('opts', options)
serviceGlobal = new Service(options)
serviceGlobal.init()
Vue.prototype.$service = this.create
}
init () {
if (!this.schema) {
let lsSchema = window.localStorage.getItem('schema')
if (lsSchema) {
let schema = JSON.parse(lsSchema)
if (typeof schema === 'object') {
this.schema = schema
} else {
window.localStorage.setItem('schema', '')
}
} else {
this.http.get(this.schemaURL).then((response) => {
this.schema = response.data
window.localStorage.setItem('schema', JSON.stringify(response.data))
this.isReady = true
if (this.schema.IsSocketsEnabled) {
let ws = glue(host, wsOptions)
window.socket = ws
this.ws = ws
this.ws.onMessage((msg) => {
if (this.store.state.auth.isValid) {
if (msg === 'connected') {
console.log('Websocket connection active') // eslint-disable-line
} else if (msg.indexOf('ping:') === 0) {
this.ws.send('pong: ' + this.store.state.auth.details.token)
} else {
msg = JSON.parse(msg)
let type = msg.Type
let data = msg.Data
if (type && data) {
this.eventBus.trigger(type, data)
}
}
}
})
}
})
}
}
}
// data methods
construct (type) {
let obj = this.schema[type]
let record = JSON.parse(JSON.stringify(obj))
return record
}
create (type, record, qs) {
if (!qs) {
qs = ''
}
// record = cleanDates(record)
this.loading = true
return this.http.post(`${this.options.env.apiURL}/v1/${type.toLowerCase()}/create${qs}`, record)
.then((response) => {
this.loading = false
return Promise.resolve(response.data)
})
.catch((error) => {
this.loading = false
return Promise.reject(error)
})
}
retrieve (type, recordID, qs) {
console.log('xxx', this)
if (!qs) {
qs = ''
}
if (recordID) {
recordID = '/' + recordID // add slash here because proxy issues
} else {
recordID = ''
}
let url = `${this.options.env.apiURL}/v1/${type.toLowerCase()}/retrieve${recordID}${qs}`
this.loading = true
return this.http.get(url)
.then((response) => {
this.loading = false
return Promise.resolve(response.data)
})
.catch((error) => {
this.loading = false
return Promise.reject(error)
})
}
paged (type, sort, direction, limit, pageNum, qs) {
if (!qs) {
qs = ''
}
if (!sort) {
sort = 'default'
}
if (!direction) {
direction = 'asc'
}
if (typeof (pageNum) === 'undefined') {
pageNum = 1
}
if (typeof (limit) === 'undefined') {
limit = 10
}
let url = `${this.options.env.apiURL}/v1/${type.toLowerCase()}/paged/${toSnakeCase(sort)}/${direction.toLowerCase()}/limit/${limit}/pagenum/${pageNum}${qs}`
this.loading = true
return this.http.get(url)
.then((response) => {
this.loading = false
return Promise.resolve(response.data)
})
.catch((error) => {
this.loading = false
return Promise.reject(error)
})
}
update (type, record, qs) {
// record = cleanDates(record)
if (!qs) {
qs = ''
}
this.loading = true
let idField = getIDField(type, record, this.isUsingULIDAsPK)
return this.http.put(`${this.options.env.apiURL}/v1/${type.toLowerCase()}/update/${idField}${qs}`, record)
.then((response) => {
this.loading = false
return Promise.resolve(response.data)
})
.catch((error) => {
this.loading = false
return Promise.reject(error)
})
}
remove (type, recordID) {
let promise = Promise.resolve(true)
// let recordID = record[type + 'ID']
if (typeof(recordID) === "undefined") {
throw new Error("No record id to delete")
}
this.loading = true
promise = this.http.delete(`${this.options.env.apiURL}/v1/${type.toLowerCase()}/delete/${recordID}`)
.then((response) => {
this.loading = false
return Promise.resolve(true)
})
.catch((error) => {
this.loading = false
return Promise.reject(error)
})
return promise
}
subscribe (type, cb) {
// start polling only once but subscribe first because the polling stops calling itself recursively in a settimeout loop if it has 0 subscribers
console.info('sub to', type) // eslint-disable-line
this.eventBus.on(type, cb)
}
unsubscribe (type, cb) {
console.info('unsub from', type) // eslint-disable-line
this.eventBus.off(type, cb)
}
save (type, record, qs) {
if (record[type + 'ID'] <= 0) {
// new
return this.create(type, record, qs)
} else {
return this.update(type, record, qs)
}
}
}
function uppercaseFirst (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
function toSnakeCase (s) {
let upperChars = s.match(/([A-Z])/g)
if (!upperChars) {
return s
}
let str = s.toString()
for (let i = 0, n = upperChars.length; i < n; i++) {
str = str.replace(new RegExp(upperChars[i]), '_' + upperChars[i].toLowerCase())
}
if (str.slice(0, 1) === '_') {
str = str.slice(1)
}
return str
}
function makeQs (qs) {
let str = ''
if (Array.isArray(qs)) { // spread operator.. new better way to do it as I can uri encode bits of the url properly
if (qs.length % 2 === 0) {
for (let i = 0; i < qs.length; i = i + 2) {
let paramName = qs[i]
let param = qs[i + 1]
str += `&${paramName}=${encodeURIComponent(param)}`
}
} else {
throw new Error('QS spread needs to be even in length.. e.g. paramName, param, paramName2, param')
}
}
if (str.length > 0) {
// str = str.replace('&', '?') // not regex so it will only replace first
str = '?qs=1' + str
}
return str
}
function checkSiteID (record, siteID, isUsingULIDAsPK) {
if (isUsingULIDAsPK) {
if ('SiteULID' in record) {
if (siteID) {
record.SiteULID = siteID
}
if (typeof (record.SiteULID) === 'undefined' || record.SiteULID == "") {
throw new Error('SiteULID not set')
}
}
} else {
if ('SiteID' in record) {
if (siteID) {
record.SiteID = siteID
}
if (typeof (record.SiteID) === 'undefined' || record.SiteID <= 0) {
throw new Error('SiteID not set')
}
}
}
}
// function cleanDates (obj) {
// for (var property in obj) {
// if (obj.hasOwnProperty(property) }) {
// if (Object.prototype.toString.call(property) === '[object Array]') {
// for (let i = 0; i < obj[property].length; i++) {
// let innerObj = obj[property][i]
// obj[property][i] = cleanDates(innerObj) // recursive on arrays
// }
// } else if (typeof (property) === 'string' && property.toLowerCase().indexOf('date') === 0) { // the convention is to start with Date i.e. DateModified so only if index === 0
// console.log(property, obj[property])
// console.log(dateformat(obj[property], 'isoUtcDateTime') })
// obj[property] = dateformat(obj[property], 'isoUtcDateTime')
// console.log(property, obj[property])
// }
// }
// }
// return obj
// }
function getIDField(type, record, isUsingULIDAsPK) {
console.log('tyep', type, record, isUsingULIDAsPK)
if (isUsingULIDAsPK) {
return record[type + 'ULID']
}
return record[type + 'ID']
}