@hosoft/restful-api-framework
Version:
Base framework of the headless cms HoServer provided by http://helloreact.cn
121 lines (105 loc) • 3.53 kB
JavaScript
/* eslint-disable guard-for-in,brace-style */
/**
* HoServer API Server Ver 2.0
* Copyright http://hos.helloreact.cn
*
* create: 2018/11/15
**/
const cacheManager = require('./cache-store')
const config = require('@hosoft/config')
const memoryStore = require('./cache-store/stores/memory')
const redisStore = require('./cache-store/stores/redis_store')
// container instance
let redisCacheInstance = null
let memoryCacheInstance = null
/**
* global cache manager
*/
class CacheManager {
/**
* factory method
*/
static getInstance(cacheType) {
let defaultCache = 'memory'
const redisConfig = config.get('db.redis')
if (redisConfig && redisConfig.host) {
defaultCache = 'redis'
} else if (cacheType === 'redis') {
cacheType = 'memory'
}
if (!cacheType) {
cacheType = defaultCache
}
if (cacheType === 'redis') {
if (redisCacheInstance) {
return redisCacheInstance
}
redisCacheInstance = cacheManager.caching({
store: redisStore,
host: redisConfig.host,
port: redisConfig.port || 6379,
auth_pass: redisConfig.password,
db: redisConfig.db || 1,
ttl: 1800 /* default 30 minutes */
})
const redisClient = redisCacheInstance.store.getClient()
redisClient.on('ready', () => {
logger.info(`connect redis success at: ${redisConfig.host}:${redisConfig.port}`)
})
redisClient.on('error', (error) => {
logger.error('redisClient error: ' + error.message)
})
logger.info('CacheManager use redis store at ' + redisConfig.host)
return redisCacheInstance
} else {
if (memoryCacheInstance) {
return memoryCacheInstance
}
memoryCacheInstance = cacheManager.caching({
store: memoryStore,
ttl: 1800
})
logger.info('CacheManager use memory store')
return memoryCacheInstance
}
}
/**
* set cache
* @param keyPrefix used for classify cache
* @param key cache key
* @param value cache value
* @param ttl timeout duration, default is 1 hour
*/
static async setCache(keyPrefix, key = '', value, ttl = 600) {
try {
return await CacheManager.getInstance().set(`${keyPrefix}${keyPrefix ? '-' : ''}${key}`, value, { ttl })
} catch (err) {
logger.error('setCache error: ' + `${keyPrefix}${keyPrefix ? '-' : ''}${key}`, err)
}
}
/**
* get cache
* @param key
*/
static async getCache(keyPrefix, key = '') {
try {
return await CacheManager.getInstance().get(`${keyPrefix}${keyPrefix ? '-' : ''}${key}`)
} catch (err) {
logger.error('getCache error: ' + `${keyPrefix}${keyPrefix ? '-' : ''}${key}`, err)
return null
}
}
/**
* delete cache
* @param key
*/
static async deleteCache(keyPrefix, key = '') {
try {
return await CacheManager.getInstance().del(`${keyPrefix}${keyPrefix ? '-' : ''}${key}`)
} catch (err) {
logger.error('deleteCache error: ' + `${keyPrefix}${keyPrefix ? '-' : ''}${key}`, err)
return null
}
}
}
module.exports = CacheManager