forked from ziaadini/nuxt-perfect-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (90 loc) · 2.76 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
import path from "path";
import RedisStore from "./lib/RedisStore";
import { serialize, deserialize } from "./lib/serializer";
export default function index({
getCacheData,
url = "redis://127.0.0.1:6379",
prefix = "r-",
appendHost = true,
disable = false,
ignoreConnectionErrors = false,
}) {
const { nuxt } = this;
nuxt.hook("render:before", (renderer) => {
const renderRoute = renderer.renderRoute.bind(renderer);
renderer.renderRoute = function (route, context) {
const host = context.req.headers.host;
const cacheData = getCacheData ? getCacheData(route, context) : null;
if (!cacheData || disable) return renderRoute(route, context);
// eslint-disable-next-line prefer-const
let { key, expire } = cacheData;
key = appendHost ? key + "-" + host : key;
const redisStore = new RedisStore(
cacheData.url || url,
false,
prefix,
true,
ignoreConnectionErrors
);
function renderAndSetCacheKey() {
return renderRoute(route, context).then(async function (result) {
if (!result.error && !result.redirected) {
await redisStore.write(key, serialize(result), expire);
}
return result;
});
}
return new Promise(async (resolve) => {
try {
const cachedResult = await redisStore.read(key);
if (cachedResult) {
resolve(deserialize(cachedResult));
} else {
resolve(renderAndSetCacheKey());
}
} catch {
resolve(renderRoute(route, context));
}
}).finally(() => {
redisStore.disconnect();
});
// try {
// function renderAndSetCacheKey() {
// return renderRoute(route, context).then(async function (result) {
// if (!result.error && !result.redirected) {
// await redisStore.write(key, serialize(result), expire)
// }
// return result
// })
// }
// return redisStore.read(key).then(function (cachedResult) {
// if (cachedResult) {
// return deserialize(cachedResult)
// }
//
// return renderAndSetCacheKey()
// })
// } catch {
// return renderRoute(route, context)
// } finally {
// redisStore.disconnect()
// }
};
});
// this.addTemplate({
// fileName: 'nuxt-perfect-cache/RedisStore.js',
// src: path.resolve(__dirname, 'lib/RedisStore.js'),
// })
this.addPlugin({
fileName: "nuxt-perfect-cache/plugin.js",
src: path.resolve(__dirname, "plugin.js"),
options: {
url,
prefix,
appendHost,
disable,
ignoreConnectionErrors,
},
});
}
module.exports.meta = require("./package.json");