keycloak-demo/utils/redis.js

49 lines
1.0 KiB
JavaScript
Raw Normal View History

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