Update index.js

This commit is contained in:
SrGooglo 2025-04-24 06:08:36 +00:00
parent 80acb13912
commit 652cd747b1

View File

@ -1,79 +1,72 @@
import Redis from "ioredis" import Redis from "ioredis"
export function composeURL({ export function composeURL({ host, port, username, password } = {}) {
host, let url = "redis://"
port,
username,
password,
} = {}) {
let url = "redis://"
if (username && password) { if (username && password) {
url += username + ":" + password + "@" url += username + ":" + password + "@"
} }
url += host ?? "localhost" url += host ?? "localhost"
if (port) { if (port) {
url += ":" + port url += ":" + port
} }
return url return url
} }
export default () => { export default (params = {}) => {
let { REDIS_HOST, REDIS_PORT, REDIS_NO_AUTH, REDIS_AUTH, REDIS_DB } = process.env let { REDIS_HOST, REDIS_PORT, REDIS_NO_AUTH, REDIS_AUTH, REDIS_DB } =
process.env
REDIS_NO_AUTH = ToBoolean(REDIS_NO_AUTH) let clientOptions = {
host: REDIS_HOST ?? "localhost",
port: REDIS_PORT ?? 6379,
lazyConnect: true,
autoConnect: false,
...params,
}
let clientOptions = { // if redis auth is provided, set username and password
host: REDIS_HOST, if (!ToBoolean(REDIS_NO_AUTH) && REDIS_AUTH) {
port: REDIS_PORT, const [user, password] = REDIS_AUTH.split(":")
lazyConnect: true,
autoConnect: false
}
if (!REDIS_NO_AUTH) { clientOptions.username = user
if (REDIS_AUTH) { clientOptions.password = password
const [user, password] = REDIS_AUTH.split(":") } else {
console.log("⚠️ Redis auth is disabled")
}
clientOptions.username = user // if redis db is provided, set db
clientOptions.password = password if (REDIS_DB) {
} clientOptions.db = REDIS_DB
} else { }
console.log("⚠️ Redis auth is disabled")
}
if (REDIS_DB) { let client = new Redis(clientOptions)
clientOptions.db = REDIS_DB
}
clientOptions = composeURL(clientOptions) client.on("error", (error) => {
console.error("❌ Redis client error:", error)
})
let client = new Redis(clientOptions.host, clientOptions.port, clientOptions) client.on("connect", () => {
console.log(`✅ Redis client connected [${process.env.REDIS_HOST}]`)
})
client.on("error", (error) => { client.on("reconnecting", () => {
console.error("❌ Redis client error:", error) console.log("🔄 Redis client reconnecting...")
}) })
client.on("connect", () => { const initialize = async () => {
console.log(`✅ Redis client connected [${process.env.REDIS_HOST}]`) return await new Promise((resolve, reject) => {
}) console.log(`🔌 Connecting to Redis client [${REDIS_HOST}]`)
client.on("reconnecting", () => { client.connect(resolve)
console.log("🔄 Redis client reconnecting...") })
}) }
const initialize = async () => { return {
return await new Promise((resolve, reject) => { client,
console.log(`🔌 Connecting to Redis client [${REDIS_HOST}]`) initialize,
}
client.connect(resolve) }
})
}
return {
client,
initialize
}
}