keycloak-demo/utils/redis.js
2021-09-01 15:20:53 +08:00

49 lines
1.0 KiB
JavaScript

const IORedis = require("ioredis");
const config = require("src/config/index.js");
class Redis extends IORedis {
constructor() {
let { prefix } = config.redis;
const { host, port, password, db } = config.redis;
if (prefix && !/:$/.test(prefix)) prefix += ":";
super({
host,
port,
password,
db,
});
this.prefix = prefix;
const self = this;
// key pattern functions
this.Key = {
/**
* SSO 登入暫存
* @param {string} s state
* @return {string}
*/
ssoLoginCache: (s) => self.getKeyWithPrefix(`sso-login:${s}`),
/**
* 儲存 Token
* @param {string} s state
* @return {string}
*/
userToken: (s) => self.getKeyWithPrefix(`token:${s}`),
};
}
/**
* combine key and prefix
* @param {string} s
* @return {string}
*/
getKeyWithPrefix(s) {
if (typeof s !== "string") throw new Error("input key not a string");
return `${this.prefix}${s}`;
}
}
module.exports = new Redis();