-
Notifications
You must be signed in to change notification settings - Fork 12
/
plugin.js
86 lines (85 loc) · 2.56 KB
/
plugin.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
import RedisStore from 'nuxt-perfect-cache/lib/RedisStore'
const options=<%= JSON.stringify(options,null,2) %>
// const options = { url: '', prefix: '', appendHost: true, disable: false }
export default ({ req }, inject) => {
inject(
'cacheFetch',
(
{
key,
expire,
disable = options.disable,
url = options.url,
prefix = options.prefix,
ignoreConnectionErrors=options.ignoreConnectionErrors
},
requestCallback
) => {
if (disable) {
return requestCallback()
}
const host = req && req.headers ? req.headers.host : ''
key = options.appendHost ? key + '-' + host : key
const redis = new RedisStore(url, true, prefix,process && process.server,ignoreConnectionErrors)
return redis.fetch(key, expire, requestCallback, true)
}
)
inject(
'cacheWrite',
(
{
key,
expire,
disable = options.disable,
url = options.url,
prefix = options.prefix,
ignoreConnectionErrors=options.ignoreConnectionErrors
},
value
) => {
if (disable) {
return new Promise(resolve=>resolve(false))
}
const host = req && req.headers ? req.headers.host : ''
key = options.appendHost ? key + '-' + host : key
const redis = new RedisStore(url, false, prefix,process && process.server,ignoreConnectionErrors)
try{
return redis.write(key,value, expire)
}catch(e){
console.error(e)
return new Promise(resolve=>resolve(false))
}
finally {
redis.disconnect()
}
}
)
inject(
'cacheRead',
(
{
key,
disable = options.disable,
url = options.url,
prefix = options.prefix,
ignoreConnectionErrors=options.ignoreConnectionErrors
}
) => {
if (disable) {
return new Promise(resolve=>resolve(null))
}
const host = req && req.headers ? req.headers.host : ''
key = options.appendHost ? key + '-' + host : key
const redis = new RedisStore(url, false, prefix,process && process.server,ignoreConnectionErrors)
try{
return redis.read(key)
}catch(e){
console.error(e)
return new Promise(resolve=>resolve(null))
}
finally {
redis.disconnect()
}
}
)
}