add storeObject
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
const Memcached = require('memcached');
|
||||
|
||||
class memcachedLib {
|
||||
constructor() {
|
||||
this._host = ''
|
||||
this._port = ''
|
||||
this._expire = 86400
|
||||
this._conn = null;
|
||||
}
|
||||
|
||||
connect() {
|
||||
this._conn = new Memcached(`${this._host}:${this._port}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* set object to memcached
|
||||
* @param {string} key
|
||||
* @param {string} val
|
||||
* @param {number} expire
|
||||
*/
|
||||
setVal(key, val, expire = this._expire) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this._conn.set(key, val, err => {
|
||||
if (err) return reject(err);
|
||||
return resolve(null);
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* get object from memcached
|
||||
* @param {string} key
|
||||
*/
|
||||
getVal(key) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this._conn.get(key, (err, data) => {
|
||||
if (err) return reject(err);
|
||||
return resolve(data);
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
set host(str) { this._host = str }
|
||||
set port(str) { this._port = str }
|
||||
set expire(str) { this._expire = str }
|
||||
}
|
||||
|
||||
module.exports = new memcachedLib();
|
||||
@@ -0,0 +1,68 @@
|
||||
const StoreObj = (() => {
|
||||
|
||||
let memStore = {};
|
||||
let maxAge = 86400000;
|
||||
|
||||
/**
|
||||
* @param {string} uuid
|
||||
* @param {object} obj
|
||||
*/
|
||||
const set = (uuid, obj) => {
|
||||
memStore[uuid] = {
|
||||
obj,
|
||||
age: Date.now() + maxAge
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} uuid
|
||||
*/
|
||||
const get = (uuid) => {
|
||||
if (uuid in memStore) {
|
||||
let s = memStore[uuid];
|
||||
if (Date.now() < s.age) {
|
||||
s.age = Date.now() + maxAge;
|
||||
return s.obj;
|
||||
} else {
|
||||
delete memStore[uuid];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} uuid
|
||||
*/
|
||||
const chkKey = (uuid) => {
|
||||
if (uuid in memStore) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} uuid
|
||||
*/
|
||||
const del = (uuid) => {
|
||||
if (uuid in memStore) delete memStore[uuid];
|
||||
}
|
||||
|
||||
const clear = () => {
|
||||
let t = Date.now();
|
||||
for (var i in memStore) {
|
||||
let s = memStore[i];
|
||||
if (s.age < t) delete memStore[i];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} uuid if not input return all
|
||||
*/
|
||||
const show = (uuid) => {
|
||||
if (uuid && uuid in memStore) return memStore[uuid];
|
||||
|
||||
return memStore;
|
||||
}
|
||||
|
||||
return {set, get, chkKey, clear, del, show };
|
||||
})()
|
||||
|
||||
module.exports = StoreObj;
|
||||
Reference in New Issue
Block a user