@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
79 lines (71 loc) • 2.4 kB
JavaScript
import { createModuleAndFile } from '../../utils/write_files.js'
/**
* Generates file content for RabbitMQ configuration.
*
* @param {string} exchange - The name of the exchange to assert.
* @param {string} fileName - The name of the file to be created.
* @param {string} folderName - The folder where the file will be created.
* @returns {string} The content to be written to the file.
*/
const rmqFileContent = `
import 'dotenv/config'
import amqplib from 'amqplib'
import { RABBITMQ_URL } from '../services/constants.js'
let channel, connection
/**
* Establishes a connection to RabbitMQ and sets up a channel with the specified exchange.
*
* @async
* @function connectQueue
* @param {string} exchange - The name of the exchange to assert.
* @throws {Error} Throws an error if the connection to RabbitMQ fails or if the exchange cannot be asserted
*/
async function connectQueue(exchange) {
try {
connection = await amqplib.connect(RABBITMQ_URL)
channel = await connection.createChannel()
await channel.assertExchange(exchange, 'direct', { durable: true })
console.log('Queue is connected')
} catch (error) {
console.error('Error in connectQueue:', error)
throw new Error('Connect Queue Has Failed')
}
}
/**
* Sends data to a specified exchange with a routing key.
*
* @async
* @function sendData
* @param {string} exchange - The name of the exchange to publish the message to.
* @param {Object} data - The data to send, serialized to JSON.
* @param {string} routingKey - The routing key for the message.
* @throws {Error} Throws an error if the channel is not initialized or if sending data fails.
*/
async function sendData(exchange, data, routingKey) {
try {
if (!channel) {
throw new Error('Channel is not initialized')
}
const originalData = JSON.stringify(data)
await channel.publish(exchange, routingKey, Buffer.from(originalData))
} catch (error) {
console.error('Error sending data to queue:', error, data)
throw error
}
}
export {
connectQueue,
sendData
}
`
/**
* Creates a file with RabbitMQ configuration.
*/
async function createRMQFile() {
const folderName = 'rabbitMQ'
const fileName = 'queue_configs.js'
await createModuleAndFile(folderName, fileName, rmqFileContent)
}
export {
createRMQFile
}