forked from theganyo/rapid-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.js
53 lines (41 loc) · 2.13 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
/****************************************************************************
Copyright (c) 2014, Scott Ganyo <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
****************************************************************************/
'use strict';
// define our Cache functionality
module.exports = function Cache(config) {
// import the Redis module
// this will make the necessary network calls to send our commands to the Redis database
var redis = require('redis');
// create the Redis client with the appropriate configuration options to connect
var redisClient = redis.createClient(config.port, config.host, config.options);
var CACHE_TTL = 30; // expire in 30 seconds
// create a function to get the twitter query value
this.get = function(query, callback) {
// issue a GET command to Redis using the query as the key
// see: http://redis.io/commands/get
redisClient.get(query, function(err, results) {
if (err) { return cb(err); }
callback(null, JSON.parse(results));
});
};
// create a function that sets the result into the database using query as the key
this.set = function(query, results, callback) {
// convert the results object to a string
results = JSON.stringify(results);
// call Redis to set the value and set a TTL on the key
// this is the same as calling SET followed by EXPIRE, but is atomic
// see: http://redis.io/commands/setex
redisClient.setex(query, CACHE_TTL, results, callback);
};
};