UNPKG

@saboosanket/code-generator

Version:

This npm package is a versatile setup tool tailored for Node.js projects, enabling users to generate customized project structures and functionalities. It supports integration with Google Cloud Platform (GCP), RabbitMQ, Redis, a Prisma query generator, an

143 lines (127 loc) 4.54 kB
import { createModuleAndFile, writeFileWithoutPrompt } from '../../utils/write_files.js' import { customErrors } from '../../base_scaffolding/custom_error.js' const redisFileContent = ` // Using ioredis over redis for robust cluster support, Sentinel handling, better reconnection strategies, retries, and advanced Redis features. import Redis from 'ioredis' import { REDIS_URL } from '../services/constants.js' // Default Redis configuration const DEFAULT_CONFIG = { retryStrategy(times) { const delay = Math.min(times * 50, 2000) if (times > 50) { return null // Stop retrying after 50 attempts } return delay }, connectTimeout: 10000, keepAlive: 30000 } /** * Creates a new Redis client with custom configuration * @param {string} connectionName - Unique name for the Redis connection * @param {object} customConfig - Optional custom configuration to override defaults * @returns {Redis} Configured Redis client instance */ function createRedisClient(connectionName, customConfig = {}) { const config = { ...DEFAULT_CONFIG, ...customConfig, connectionName } const client = new Redis(REDIS_URL, config) client.on('error', function (err) { console.error(\`Redis \${connectionName} connection error:\`, err) }) client.on('connect', function () { console.log(\`Redis \${connectionName} connected\`) }) client.on('ready', function () { console.log(\`Redis \${connectionName} ready\`) }) client.on('close', function () { console.log(\`Redis \${connectionName} connection closed\`) }) client.on('reconnecting', function () { console.log(\`Redis \${connectionName} reconnecting\`) }) return client } /** * Sets data in Redis with an optional expiration time (TTL) * @param {string} key - The key under which the data will be stored * @param {string|object} value - The value to be stored in Redis (can be a string or an object) * @param {number} [ttl] - Optional time-to-live (TTL) in seconds for the cache * @returns {Promise} Resolves when the data is set successfully */ async function setDataRedis(client, key, value, ttl = null) { try { const valueToStore = typeof value === 'object' ? JSON.stringify(value) : value if (ttl) { await client.setex(key, ttl, valueToStore) } else { await client.set(key, valueToStore) } console.log(\`Data set for key: \${key}\`) } catch (err) { console.error(\`Error setting data for key \${key}:\`, err) } } /** * Gets data from Redis by key * @param {string} key - The key to fetch data from Redis * @returns {Promise} Resolves with the data if found, otherwise null */ async function getDataRedis(client, key) { try { const data = await client.get(key) if (data) { // Parse the data if it was stored as a JSON string return data } console.log(\`No data found for key: \${key}\`) return null } catch (err) { console.error(\`Error getting data for key \${key}:\`, err) return null } } /** * Deletes data from Redis by key. * * @param {Object} client - The Redis client instance. * @param {string} key - The key to delete from Redis. * @returns {Promise<boolean|null>} Resolves with: * - 'true' if the key was successfully deleted. * - 'false' if the key does not exist or could not be deleted. * - 'null' if an error occurs during deletion. * * @throws {Error} Logs the error and returns 'null' if an exception occurs during deletion. * */ async function deleteDataRedis(client, key) { try { const result = await client.del(key) // Attempt to delete the key if (result === 1) { console.log(\`Key "\${key}" deleted successfully.\`) return true // Return true if the key was successfully deleted } console.log(\`Key "\${key}" not found or could not be deleted.\`) return false } catch (err) { console.error(\`Error deleting key "\${key}":\`, err) return null } } export { setDataRedis, getDataRedis, deleteDataRedis } ` async function createRedisFile() { const folderName = 'redis' const fileName = 'redis.js' await createModuleAndFile(folderName, fileName, redisFileContent) await writeFileWithoutPrompt('services', 'custom_error.js', customErrors) } export { createRedisFile }