import { secretPromise } from '../aws-secret-manager/aws-secret-manager'; const Sequelize = require('sequelize'); type rdsConfigType = { host: string; dialect: string; database: string; username: string; password?: string; url: string; port: string; }; type rdsConfigMappingValueType = { rdsConfig?: rdsConfigType; fetchPasswordFromASM: boolean; sequelizeInstanceName: string; }; type rdsConfigMappingType = { [key: string]: rdsConfigMappingValueType; }; type sequelizeInstancesMappingType = { [key: string]: Object | undefined; }; type instanceRetryCount = { [key: string]: number; }; let sequelizeInstances: sequelizeInstancesMappingType = { globalSequelizeInstance: undefined, }; let sequelizeInstancesRetryCount: instanceRetryCount = { globalSequelizeInstance: 0, }; const rdsConfigMapping: rdsConfigMappingType = { default: { fetchPasswordFromASM: true, sequelizeInstanceName: 'globalSequelizeInstance', }, }; /** * The function `authenticateSequelizer` is used to authenticate a Sequelize instance with a database. * @param {any} sequelizeInstance - The `sequelizeInstance` parameter is an instance of the Sequelize * library, which is used to interact with the database. It represents a connection to the database and * provides methods for executing queries and managing database models. * @returns The `authenticateSequelizer` function is returning a promise that resolves to the result of * calling the `authenticate` method on the `sequelizeInstance`. */ export const authenticateSequelizer = async (sequelizeInstance: any) => { try { return await sequelizeInstance.authenticate(); } catch (error) { console.error('Unable to connect to the database:', error); throw new Error(error); } }; /** * The function creates and returns a Sequelize instance using the provided RDS configuration. * @param {rdsConfigType} rdsConfig - The `rdsConfig` parameter is an object that contains the * configuration details for connecting to an RDS (Relational Database Service) instance. It typically * includes the following properties: * @returns a Sequelize instance. */ export const createSequelizeInstance = async (rdsConfig: rdsConfigType) => { try { const sequelizeInstance = new Sequelize( rdsConfig.database, rdsConfig.username, rdsConfig.password ?? '', { host: rdsConfig.host, dialect: rdsConfig.dialect, } ); await authenticateSequelizer(sequelizeInstance); return sequelizeInstance; } catch (error) { throw new Error(error); } }; /** * The function creates a connection to AWS Secrets Manager and retrieves a password from a specified * secret. * @param {any} awsASMUsername - The `awsASMUsername` parameter is the username or identifier used to * access the AWS Secrets Manager. It is typically a string value that represents the username * associated with the secret. * @param {string} awsSecretName - The `awsSecretName` parameter is the name of the secret in AWS * Secrets Manager that contains the password for the connection. * @returns the password from the secret data obtained from AWS Secrets Manager. */ export const createConnectionToASM = async ( awsASMUsername: any, awsSecretName: string ): Promise => { try { const secretData: any = await secretPromise(awsASMUsername, awsSecretName); const password = secretData['password']; return password; } catch (error) { throw new Error(error); } }; /** * The function updates the RDS configuration with a password retrieved from AWS Secrets Manager. * @param {rdsConfigType} rdsConfig - The `rdsConfig` parameter is of type `rdsConfigType`, which is * likely a custom type or interface representing the configuration for an RDS (Relational Database * Service) instance. * @param {any} awsASMUsername - The `awsASMUsername` parameter is the username used to authenticate * with AWS Secrets Manager. It is used to retrieve the password for the RDS configuration from the * secret stored in AWS Secrets Manager. * @param {string} secretName - The `secretName` parameter is a string that represents the name of the * secret in AWS Secrets Manager that contains the password for the RDS database. * @returns the updated `rdsConfig` object with the `password` property updated with the password * retrieved from the AWS Secrets Manager. */ export const updateRDSConfigWithASMPwd = async ( rdsConfig: rdsConfigType, awsASMUsername: any, secretName: string ) => { try { let updatedRdsConfig = rdsConfig; const password = await createConnectionToASM(awsASMUsername, secretName); updatedRdsConfig.password = password; return updatedRdsConfig; } catch (error) { throw new Error(error); } }; /** * The function `getSequelizeInstance` is an asynchronous function that retrieves or creates a * Sequelize instance based on the provided configuration and mapping. * @param {string} [rdsConfigMappingType=default] - The `rdsConfigMappingType` parameter is a string * that represents the type of RDS configuration mapping to use. It is used to determine the specific * configuration settings for connecting to the RDS database. * @param {rdsConfigType} rdsConfig - The `rdsConfig` parameter is an object that contains the * configuration details for connecting to the RDS (Relational Database Service) instance. It typically * includes properties such as `host`, `port`, `database`, `username`, and `password`. * @param {any} awsASMUsername - The `awsASMUsername` parameter is the username used to authenticate * with AWS Secrets Manager. It is used to fetch the password for the RDS configuration from AWS * Secrets Manager. * @param {string} secretName - The `secretName` parameter is a string that represents the name of the * secret in AWS Secrets Manager that contains the password for the RDS database. * @returns a Sequelize instance. */ export const getSequelizeInstance = async ( rdsConfigMappingType: string = 'default', rdsConfig: rdsConfigType, awsASMUsername: any, secretName: string ) => { const foundRdsConfigMapping = rdsConfigMapping[rdsConfigMappingType]; const { fetchPasswordFromASM, sequelizeInstanceName } = foundRdsConfigMapping || {}; let finalRdsConfig = rdsConfig; try { if (!sequelizeInstances[sequelizeInstanceName]) { if (fetchPasswordFromASM) { finalRdsConfig = await updateRDSConfigWithASMPwd( finalRdsConfig, awsASMUsername, secretName ); } sequelizeInstances[sequelizeInstanceName] = await createSequelizeInstance( finalRdsConfig ); } else { await authenticateSequelizer(sequelizeInstances[sequelizeInstanceName]); } sequelizeInstancesRetryCount[sequelizeInstanceName] = 0; return sequelizeInstances[sequelizeInstanceName]; } catch (error) { if (sequelizeInstancesRetryCount[sequelizeInstanceName] >= 2) { console.error('Sequelize Instance Generation Failed: ', error); sequelizeInstancesRetryCount[sequelizeInstanceName] = 0; throw error; } sequelizeInstancesRetryCount[sequelizeInstanceName]++; delete sequelizeInstances[sequelizeInstanceName]; getSequelizeInstance( rdsConfigMappingType, rdsConfig, awsASMUsername, secretName ); } };