-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.js
234 lines (210 loc) · 6.37 KB
/
cache.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
import get from 'lodash/get';
import split from 'lodash/split';
import zip from 'lodash/zip';
import zipObject from 'lodash/zipObject';
import map from 'lodash/map';
import isNull from 'lodash/isNull';
import Redis from 'ioredis';
import {
USER_CONSTANT,
USER_WISHLIST_CONSTANT,
} from 'grandus-lib/constants/SessionConstants';
let client = null;
if (process.env.CACHE_ENABLED) {
if (process.env.CACHE_USE_CLUSTER) {
let clusterConfigExploded = zip(
split(process.env.CACHE_PORT, ','),
split(process.env.CACHE_HOST, ','),
);
let clusterConfig = map(clusterConfigExploded, clusterConfigEntry => {
return zipObject(['port', 'host'], clusterConfigEntry);
});
client = new Redis.Cluster(clusterConfig);
} else {
client = new Redis(
process.env.CACHE_PORT ? process.env.CACHE_PORT : undefined,
process.env.CACHE_HOST ? process.env.CACHE_HOST : undefined,
{ lazyConnect: true },
);
}
}
/**
* Internal function for getting user AccessToken from session. If user is not logged in, result is unified 0
*
* @param {Object} req - url request object
*/
const extractUserAccessToken = req => {
let user = {};
if (req && req?.session) {
user = get(req.session, USER_CONSTANT);
}
return get(user, 'accessToken', 0);
};
/**
* Initialized Redis client
*/
export default client;
/**
* Generate unified cache KEY from provided array enriched with env prefix and suffix
*
* @param {Array} keyParts - parts which will be concated
*/
export const getCacheKey = (keyParts = []) => {
return [
process.env.CACHE_KEY_PREFIX ? process.env.CACHE_KEY_PREFIX : 'prefix',
process.env.HOST ? process.env.HOST : 'undefined-host',
...keyParts,
process.env.CACHE_KEY_SUFFIX ? process.env.CACHE_KEY_SUFFIX : 'suffix',
]
.join('-')
.replace(/ /gi, '--'); //regex to replace all occurances of ' '
};
/**
* Generate unified cache KEY from request
*
* @param {object} req
*
* @returns {string} User AccessToken or 0
*/
export const getCacheKeyByRequest = req => {
return getCacheKey([get(req, 'url', '/'), extractUserAccessToken(req)]);
};
export const getCacheKeyByProps = props => {
return getCacheKey(['props', JSON.stringify(props)]);
};
/**
* Generate unified cache KEY by type
*
* @param {options} type enumerated set of predefined options
* @param {object} options specified options which variate specific options
*/
export const getCacheKeyByType = (type = 'request', options = {}) => {
switch (type) {
case 'webinstance':
return getCacheKey(['system-webinstance']);
case 'header':
return getCacheKey(['system-layout-header']);
case 'footer':
return getCacheKey(['system-layout-footer']);
case 'custom':
const cacheParts = ['custom-key', ...get(options, 'cacheKeyParts', [])];
if (get(options, 'cacheKeyUseUser', true)) {
cacheParts.push(extractUserAccessToken(get(options, 'req', null)));
}
return getCacheKey(cacheParts);
case 'request':
return getCacheKeyByRequest(get(options, 'req', null));
case 'props':
return getCacheKeyByProps(options);
case 'wishlist':
return getCacheKey([
USER_WISHLIST_CONSTANT,
extractUserAccessToken(get(options, 'req', null)),
]);
default:
return getCacheKey([`default-${type}`]);
}
};
/**
* Get data from Redis cache according to props
*
* @param {instance} cache sinstance of previosly initiated redis client
* @param {object} options specified options which variate specific options
*/
export const getCachedDataProps = async (cache, props = {}, cacheId = '') => {
return await getCachedData({}, cache, {
cacheKeyType: 'props',
cacheId: cacheId,
...props,
});
};
/**
* Get data from Redis cache
*
* @param {object} req nextjs request object
* @param {instance} cache sinstance of previosly initiated redis client
* @param {object} options specified options which variate specific options
*/
export const getCachedData = async (req, cache, options = {}) => {
if (!cache) return false;
const cacheKey =
get(options, 'cacheKey',
getCacheKeyByType(get(options, 'cacheKeyType'), { req: req, ...options }) +
getLocalSuffix(req),
);
const data = await cache.get(
cacheKey,
// (err) => console.error(err)
);
if (!data) {
return false;
}
return JSON.parse(data);
};
/**
* Get data from Redis cache and output it to response.
* used mainly by API
*
* @param {object} req nextjs request object
* @param {object} res nextjs response object
* @param {instance} cache sinstance of previosly initiated redis client
* @param {object} options specified options which variate specific options
*/
export const outputCachedData = async (req, res, cache, options = {}) => {
if (!cache) return false;
const cachedData = await getCachedData(req, cache, options);
if (isNull(cachedData) || cachedData == false) return false;
if (!isNull(res)) {
res.setHeader('Grandus-Cached-Data', true);
res.status(200).json(cachedData);
}
return true;
};
/**
* Save data to Redis cache according to props
*
* @param {instance} cache sinstance of previosly initiated redis client
* @param {object} data data to be saved in cache
* @param {object} options specified options which variate specific options
*/
export const saveDataToCacheProps = async (
cache,
data,
props = {},
cacheId = '',
) => {
return await saveDataToCache({}, cache, data, {
cacheKeyType: 'props',
cacheId: cacheId,
...props,
});
};
/**
* Save data to Redis cache
*
* @param {object} req nextjs request object
* @param {instance} cache sinstance of previosly initiated redis client
* @param {object} data data to be saved in cache
* @param {object} options specified options which variate specific options
*/
export const saveDataToCache = async (req, cache, data, options = {}) => {
if (!cache) return false;
let cacheTime = get(options, 'time');
if (!cacheTime) {
cacheTime = process.env.CACHE_TIME ? process.env.CACHE_TIME : 60;
}
const cacheKey =
get(options, 'cacheKey',
getCacheKeyByType(get(options, 'cacheKeyType'), { req: req, ...options }) +
getLocalSuffix(req),
);
try {
cache.set(cacheKey, JSON.stringify(data), 'EX', cacheTime);
} catch (error) {
console.error(error);
}
};
const getLocalSuffix = req => {
const locale = get(req, 'cookies.NEXT_LOCALE');
return locale ? `.${locale}` : '';
};