-
Notifications
You must be signed in to change notification settings - Fork 3
/
sqlCached.js
42 lines (34 loc) · 1.01 KB
/
sqlCached.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
'use strict';
var crypto = require('crypto');
var NodeCache = require('node-cache');
var sql = require('./sql');
var queryCache = new NodeCache();
function generateQueryHash(query, params) {
var fullQuery = query + (params || []).join(',');
return crypto.createHash('md5').update(fullQuery).digest('hex');
}
function checkCache(cacheKey, callback) {
queryCache.get(cacheKey, (err, value) => {
if (err || value === undefined) {
return callback(err || new Error('Value not found'));
}
callback(null, value);
});
}
function runQuery(query, params, callback) {
var queryHash = generateQueryHash(query, params);
checkCache(queryHash, (err, value) => {
if (value) {
console.info('Served from cache', queryHash);
return callback(null, value);
}
sql.runQuery(query, params, function (err, result) {
if (err) {
return callback(err);
}
queryCache.set(queryHash, result);
callback(null, result);
});
});
}
module.exports.runQuery = runQuery;