Created
July 20, 2014 13:24
-
-
Save CarterTsai/f01663e4c9d003cef531 to your computer and use it in GitHub Desktop.
Simulate azure cache and Add expired time function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var CACHE = {}; | |
var cache = function() { | |
var self = this; | |
self.memory = {}; | |
}; | |
cache.put = function(key, data , cb) { | |
var self = this; | |
self.memory = {key:data}; | |
cb(true); | |
}; | |
cache.get = function(key, cb) { | |
var self = this; | |
cb(false, self.memory["key"]); | |
}; | |
// | |
CACHE.write_json = function(key ,value ,cb) { | |
var buf = new Buffer(JSON.stringify(value)); | |
var json = JSON.stringify(buf); | |
var _struct = { | |
data: json, | |
time: new Date() | |
} | |
cache.put(key, _struct, function (error) { | |
if (error) { | |
cb(false); | |
} else { | |
cb(true); | |
} | |
}); | |
}; | |
CACHE.check_no_expired = function(write_time, cache_mins) { | |
var now = new Date("2014/07/20 20:49"); | |
var diffs = now - write_time ; | |
var diffMins = Math.round(((diffs % 86400000) % 3600000) / 60000); | |
console.log("now:"+now); | |
console.log("write:"+write_time); | |
console.log(diffMins); | |
console.log(cache_mins); | |
return (diffMins < cache_mins); | |
}; | |
CACHE.read_json = function(key, cache_time, cb) { | |
cache.get(key, function (error, value) { | |
console.log(value); | |
if (error) { | |
cb([], false); | |
} else { | |
if(!value) { // value is null | |
cb([], false); | |
} else { | |
if(!!value.time) { | |
if(CACHE.check_no_expired(value.time, cache_time)) { | |
var data = new Buffer(JSON.parse(value.data)); | |
var json = JSON.parse(data.toString('utf8')); | |
cb(json, true); | |
} else { | |
cb([], false); | |
} | |
} else { | |
cb([], false); | |
} | |
} | |
} | |
}); | |
}; | |
console.log("write {'data:'a1'} to cache" ); | |
CACHE.write_json("test",{"data":'a1'}, function(error) { | |
console.log("has error " + (error)?"yes":"no"); | |
CACHE.read_json("test", 5,function(data, error) { | |
console.log(data); | |
console.log(error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment