92 lines
2.0 KiB
JavaScript
92 lines
2.0 KiB
JavaScript
|
const Redis = require('ioredis')
|
||
|
const config = require('@config/index')
|
||
|
|
||
|
class RedisStore {
|
||
|
constructor () {
|
||
|
this._redis = new Redis(config.redis.port, config.redis.host)
|
||
|
this._expires = 86400 // day (sec)
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* set data to redis
|
||
|
* @param {string} key
|
||
|
* @param {string|object} data string or json
|
||
|
* @param {number} expires default 1 day
|
||
|
*/
|
||
|
set (key, data = null, expires = null) {
|
||
|
if (!key || typeof key !== 'string') return
|
||
|
if (key.trim().length === 0) return
|
||
|
if (typeof data === 'object') {
|
||
|
try {
|
||
|
data = JSON.stringify(data)
|
||
|
} catch (err) {}
|
||
|
}
|
||
|
|
||
|
if (expires === null || !isFinite(expires)) expires = this._expires
|
||
|
|
||
|
let args = [`${key}`, data]
|
||
|
if (expires > 0) args.push('EX', expires)
|
||
|
|
||
|
this._redis.set(...args)
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* get data from redis
|
||
|
* @param {string} key
|
||
|
* @param {boolean=} toJSON parse data to json (default true)
|
||
|
*/
|
||
|
async get (key, toJSON = true) {
|
||
|
if (!key || typeof key !== 'string') return null
|
||
|
if (key.trim().length === 0) return null
|
||
|
let self = this
|
||
|
let data = null
|
||
|
try {
|
||
|
data = await self._redis.get(`${key}`)
|
||
|
} catch (err) {
|
||
|
return null
|
||
|
}
|
||
|
if (toJSON === true) {
|
||
|
try {
|
||
|
data = JSON.parse(data)
|
||
|
} catch (err) {
|
||
|
return null
|
||
|
}
|
||
|
}
|
||
|
return data
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* delete data
|
||
|
* @param {string} key
|
||
|
*/
|
||
|
del (key) {
|
||
|
if (!key || typeof key !== 'string') return null
|
||
|
if (key.trim().length === 0) return null
|
||
|
this._redis.del(`${key}`)
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* show all this project namespace data
|
||
|
*/
|
||
|
async show () {
|
||
|
// return this._store
|
||
|
let self = this
|
||
|
let json = {}
|
||
|
let keys = await this._redis.keys(`*`)
|
||
|
for (let i in keys) {
|
||
|
try {
|
||
|
let data = await this._redis.get(keys[i])
|
||
|
let j = JSON.parse(data)
|
||
|
let k = keys[i].replace(self._namespace, '')
|
||
|
json[k] = j
|
||
|
} catch (err) {
|
||
|
continue
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return json
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = new RedisStore()
|