-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
114 lines (102 loc) · 2.69 KB
/
index.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
const gcs = require('@google-cloud/storage')
const Promise = require('bluebird')
const redis = require('redis')
const request = require('superagent')
const promiseRetry = require('promise-retry')
Promise.promisifyAll(redis.RedisClient.prototype)
Promise.promisifyAll(redis.Multi.prototype)
class RedisLocalStore {
constructor (config, options) {
this.options = options
this.client = redis.createClient(config.connection)
}
get (key) {
return this.client.getAsync(key).then(result => {
if (result) {
return result
}
return null
})
}
// TTL in seconds
set (key, value, ttl = 60) {
this.client.setAsync(key, value, 'EX', ttl)
}
}
class GoogleCloudCache {
constructor (config, localStore) {
this.store = localStore
this.storage = gcs(config.connection)
this.uploads = {}
this.bucketName = config.options.bucket
this.bucket = this.storage.bucket(this.bucketName)
}
get (key) {
return this.store.get(key).then(result => {
if (result) {
return result
}
return null
})
.catch(err => {
return Promise.reject(err)
})
}
set (key, uri, ttl = 60) {
return this._write(key, uri).then(cacheUri => {
this.store.set(key, cacheUri, ttl)
return cacheUri
})
.catch(err => {
return Promise.reject(err)
})
}
_write (key, uri) {
if (this.uploads[key] === undefined) {
this.uploads[key] = true
const name = Buffer.from(uri).toString('hex')
const file = this.bucket.file(name)
return Promise.resolve(
promiseRetry((retry, number) => {
return new Promise((resolve, reject) => {
request.get(uri)
.pipe(file.createWriteStream())
.on('error', err => reject(err))
.on('finish', () => resolve())
})
.catch(retry)
}, {
retries: 3
})
)
.then(() => `https://storage.googleapis.com/${this.bucketName}/${name}`)
.catch(err => {
return Promise.reject(err)
})
.finally(() => {
delete this.uploads[key]
})
}
return null
}
}
module.exports = (config = {}) => {
if (!config.store || !config.cache) {
throw new Error('invalid local or remote configuration')
}
let store
switch (config.store.client) {
case 'redis':
store = new RedisLocalStore(config.store)
break
default:
return Promise.reject(new Error('unknown store client type'))
}
let cache
if (config.cache.client === 'gcloud') {
cache = new GoogleCloudCache(config.cache, store)
} else {
return Promise.reject(new Error('unknown cache client type'))
}
return Promise.resolve(cache)
}