-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaptran.js
More file actions
52 lines (46 loc) · 1.59 KB
/
captran.js
File metadata and controls
52 lines (46 loc) · 1.59 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
'use strict'
const Wmata = require('./captran-wmata')
const Redis = require('ioredis')
module.exports = class Captran {
constructor (options) {
if (!options) {
options = {}
}
this.options = options
this.wmata = new Wmata(options)
this.dataCache = new Redis(options.ioredis)
this.debugMode = options.debugMode || true // defaults to true
}
remember (params, json, callback) {
let key = JSON.stringify(params)
if (this.debugMode) json.captranDebug.cached = true
this.dataCache.set(key, JSON.stringify(json)).catch(e => console.error)
json.ttl
? this.dataCache.expire(key, json.ttl).catch(e => console.error)
: this.dataCache.expire(key, 60 * 60 * 2).catch(e => console.error)
return callback // if
? callback(null, json)
: Promise.resolve(json)
}
queryWmata (params, callback) {
return callback // if
? this.wmata.query(params, (error, json) => {
if (error) callback(error)
this.remember(params, json, callback)
}) // else return promise
: this.wmata.query(params).then(json => this.remember(params, json))
}
query (params, callback) {
let key = JSON.stringify(params)
return callback
? this.dataCache.get(key, (error, result) => {
if (error) callback(error)
else if (result) callback(null, result)
else this.queryWmata(params, callback)
})
: this.dataCache.get(key).then(result => result // if not null
? Promise.resolve(JSON.parse(result)) // return it as thenable
: this.queryWmata(params) // else get new results
)
}
}