lora-project/server-api/libs/memcache_lib.js

49 lines
1.0 KiB
JavaScript

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
*/
async setVal (key, val, expire = this._expire) {
return new Promise((resolve, reject) => {
this._conn.set(key, val, expire, err => {
if (err) return reject(err)
return resolve(null)
})
})
}
/**
* get object from memcached
* @param {string} key
*/
async 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()