r2c-url-shortener
Version:
Quick, Reusable, Reliable, Collision-free URL shortener with Redis and Postgres support
48 lines (41 loc) • 1.04 kB
JavaScript
let pool = null;
let redisClient = null;
let redisReady = null;
const initPostgres = ({ username, password, host, database, port }) => {
const { Pool } = require('pg');
pool = new Pool({
user: username,
password,
host,
database,
port,
});
return pool;
};
const initRedis = ({ url }) => {
const redis = require('redis');
redisClient = redis.createClient({ url });
redisReady = redisClient.connect()
.then(() => {})
.catch(err => {
redisClient = null;
});
};
const waitForRedis = async () => {
if (!redisClient || !redisReady) throw new Error("Redis not initialized");
await redisReady;
return redisClient;
};
const getConnections = async () => {
if (!pool || !redisClient) {
throw new Error("Postgres or Redis not initialized. Please call initPostgres() and initRedis() first.");
}
await redisReady;
return { pool, redisClient };
};
module.exports = {
initPostgres,
initRedis,
getConnections,
waitForRedis,
};