Skip to content

The Refactored Code

View in GitHub

src/index.ts

import { ExecuteStandardPTOperationsParamsSchema } from './schemas'
import type { DB } from './db/types'
import {
type IdObject, PaymentMethod,
type ExecuteStandardPTOperationsParams
} from './types'
// Dependencies required for executing standard PT operations.
interface Dependencies {
db: DB
}
/**
* Executes standard payment transaction operations.
* @param {Dependencies} dependencies - The database dependencies required for the operation.
* @returns A function that takes `ExecuteStandardPTOperationsParams` and returns a promise that resolves to an `IdObject`.
*/
export default ({
db: {
insertPayment,
insertFedNowPayment,
insertLedgerEntry,
insertPromotionLedgerEntry,
insertTransactionRecord
}
}: Dependencies) =>
async (params: ExecuteStandardPTOperationsParams) => {
ExecuteStandardPTOperationsParamsSchema.parse(params)
const {
userPurchaseInformation: {
payeeId,
payerId,
payerAccountId,
payeeAccountId,
developerId,
amount,
interactionTypeId,
paymentMethod
},
promotionInformation: { promoAmount },
sqlTransactionId
} = params
const ledgerEntries: string[] = []
// Initialize the ID object to store various transaction IDs.
const idObj: IdObject = {
primaryPaymentID: null,
customerLedgerEntryID: null,
pursTransactionID: null // To be set after transaction record insertion.
}
// Insert a payment record and update the ID object.
const paymentId = await insertPayment({
payerId,
payeeId,
developerId,
amount,
interactionTypeId,
paymentMethod,
sqlTransactionId
})
idObj.primaryPaymentID = paymentId
// Handle FedNow payment method.
if (
paymentMethod === PaymentMethod.FedNow &&
amount > 0 &&
(payerAccountId != null) &&
(payeeAccountId != null)
) {
const fedNowPaymentId = await insertFedNowPayment({
paymentId,
payerAccountId,
payeeAccountId,
sqlTransactionId
})
idObj.primaryFedNowPaymentID = fedNowPaymentId
}
// Insert a ledger entry and update the ID object.
const ledgerId = await insertLedgerEntry({
payerId,
payeeId,
developerId,
amount,
interactionTypeId,
sqlTransactionId
})
idObj.customerLedgerEntryID = ledgerId
ledgerEntries.push(ledgerId)
// Handle promotion ledger entry if a promo amount is present.
if ((promoAmount != null) && promoAmount > 0) {
const promotionLedgerId = await insertPromotionLedgerEntry({
developerId,
payeeId,
payerId,
promoAmount,
interactionTypeId,
sqlTransactionId
})
ledgerEntries.push(promotionLedgerId)
idObj.promotionLedgerEntryID = promotionLedgerId
}
// Insert a transaction record and finalize the ID object.
const pursTransactionId = await insertTransactionRecord({
ledgerEntries: ledgerEntries as [string, ...string[]],
sqlTransactionId
})
idObj.pursTransactionID = pursTransactionId
return idObj
}

src/schemas.ts

import { z } from 'zod'
import { PaymentMethod } from './types'
// Schema for UserPurchaseInformation, detailing IDs, account IDs, amount, interaction type, and payment method.
const UserPurchaseInformationSchema = z.object({
payeeId: z.string().length(32), // 32-character string for Payee ID
payerId: z.string().length(32), // 32-character string for Payer ID
payerAccountId: z.string().length(32).optional(), // Optional 32-character string for Payer Account ID
payeeAccountId: z.string().length(32).optional(), // Optional 32-character string for Payee Account ID
developerId: z.string().length(32), // 32-character string for Developer ID
amount: z.number().nonnegative(), // Non-negative number for transaction amount
interactionTypeId: z.number(), // Numeric ID for interaction type
paymentMethod: z.nativeEnum(PaymentMethod) // Enum for Payment Method
})
// Schema for PromotionInformation, including an optional non-negative promotional amount.
const PromotionInformationSchema = z.object({
promoAmount: z.number().nonnegative().optional() // Optional non-negative number for promotional amount
})
// Schema for ExecuteStandardPTOperationsParams, including user purchase information, promotion information, and SQL transaction ID.
export const ExecuteStandardPTOperationsParamsSchema = z.object({
userPurchaseInformation: UserPurchaseInformationSchema, // Schema for user purchase information
promotionInformation: PromotionInformationSchema, // Schema for promotion information
sqlTransactionId: z.string().length(32) // 32-character string for SQL transaction ID
})

src/types/index.ts

import { type z } from 'zod'
import { type ExecuteStandardPTOperationsParamsSchema } from '../schemas'
/**
* Enumerates the available payment methods.
*
* @enum {number}
* @property {number} FedNow - Represents FedNow payment method.
* @property {number} Card - Represents Card payment method.
*/
export enum PaymentMethod {
FedNow = 0,
Card = 1,
}
/**
* Enumerates the possible statuses of a payment.
*
* @enum {number}
* @property {number} COMPLETE - Indicates that the payment is complete.
* @property {number} PENDING - Indicates that the payment is pending.
*/
export enum PaymentStatus {
COMPLETE = 4,
PENDING = 5,
}
/**
* Represents the information related to a user's purchase.
*
* @interface
* @property {string} payerId - The unique identifier of the payer.
* @property {string} payeeId - The unique identifier of the payee.
* @property {string} [payerAccountId] - The account identifier of the payer (optional).
* @property {string} [payeeAccountId] - The account identifier of the payee (optional).
* @property {string} developerId - The unique identifier of the developer.
* @property {number} amount - The amount of the transaction.
* @property {number} interactionTypeId - The type of interaction.
* @property {PaymentMethod} paymentMethod - The method of payment.
*/
export interface UserPurchaseInformation {
payerId: string
payeeId: string
developerId: string
amount: number
interactionTypeId: number
paymentMethod: PaymentMethod
payerAccountId?: string
payeeAccountId?: string
}
/**
* Contains information about a promotion.
*
* @interface
* @property {number} [promoAmount] - The amount of the promotion (optional).
*/
export interface PromotionInformation {
promoAmount?: number
}
// Type alias for nullable string
type NullableString = string | null
/**
* Represents various IDs associated with a transaction.
*
* @interface
* @property {NullableString} primaryPaymentID - The primary payment ID (can be null).
* @property {NullableString} customerLedgerEntryID - The customer ledger entry ID (can be null).
* @property {NullableString} pursTransactionID - The PURS transaction ID (can be null).
* @property {string} [primaryFedNowPaymentID] - The primary FedNow payment ID (optional).
* @property {string} [promotionLedgerEntryID] - The promotion ledger entry ID (optional).
*/
export interface IdObject {
primaryPaymentID: NullableString
customerLedgerEntryID: NullableString
pursTransactionID: NullableString
primaryFedNowPaymentID?: string
promotionLedgerEntryID?: string
}
/**
* Type representing the parameters for executing standard PT operations.
* This type is inferred from the `ExecuteStandardPTOperationsParamsSchema`.
*
* @typedef {z.infer<typeof ExecuteStandardPTOperationsParamsSchema>} ExecuteStandardPTOperationsParams
*/
export type ExecuteStandardPTOperationsParams = z.infer<typeof ExecuteStandardPTOperationsParamsSchema>

src/db/schemas.ts

import { z } from 'zod'
import { PaymentMethod } from '../types'
// Schema for InsertPaymentParams, validating parameters required for inserting a payment.
export const InsertPaymentParamsSchema = z.object({
payerId: z.string().length(32), // 32-character string for payer ID
payeeId: z.string().length(32), // 32-character string for payee ID
developerId: z.string().length(32), // 32-character string for developer ID
amount: z.number().nonnegative(), // Non-negative number for amount
interactionTypeId: z.number(), // Numeric ID for interaction type
paymentMethod: z.nativeEnum(PaymentMethod), // Enum for payment method
sqlTransactionId: z.string().length(32) // 32-character string for SQL transaction ID
})
// Schema for InsertFedNowPaymentParams, validating parameters required for inserting a FedNow payment.
export const InsertFedNowPaymentParamsSchema = z.object({
paymentId: z.string().length(32), // 32-character string for payment ID
payerAccountId: z.string().length(32), // 32-character string for payer account ID
payeeAccountId: z.string().length(32), // 32-character string for payee account ID
sqlTransactionId: z.string().length(32) // 32-character string for SQL transaction ID
})
// Schema for InsertLedgerEntryParams, validating parameters required for inserting a ledger entry.
export const InsertLedgerEntryParamsSchema = z.object({
payerId: z.string().length(32), // 32-character string for payer ID
payeeId: z.string().length(32), // 32-character string for payee ID
developerId: z.string().length(32), // 32-character string for developer ID
amount: z.number(), // Number for amount
interactionTypeId: z.number(), // Numeric ID for interaction type
sqlTransactionId: z.string() // String for SQL transaction ID
})
// Schema for InsertPromotionLedgerEntryParams, validating parameters required for inserting a promotion ledger entry.
export const InsertPromotionLedgerEntryParamsSchema = z.object({
developerId: z.string().length(32), // 32-character string for developer ID
payerId: z.string().length(32), // 32-character string for payer ID
payeeId: z.string().length(32), // 32-character string for payee ID
promoAmount: z.number().nonnegative(), // Non-negative number for promotional amount
interactionTypeId: z.number(), // Numeric ID for interaction type
sqlTransactionId: z.string().length(32) // 32-character string for SQL transaction ID
})
// Schema for InsertTransactionRecordParams, validating parameters required for inserting a transaction record.
export const InsertTransactionRecordParamsSchema = z.object({
ledgerEntries: z.array(z.string()).nonempty(), // Non-empty array of ledger entry strings
sqlTransactionId: z.string().length(32) // 32-character string for SQL transaction ID
})

src/db/types.ts

import { type z } from 'zod'
import {
type InsertPaymentParamsSchema,
type InsertFedNowPaymentParamsSchema,
type InsertLedgerEntryParamsSchema,
type InsertPromotionLedgerEntryParamsSchema,
type InsertTransactionRecordParamsSchema
} from './schemas'
/**
* Represents the parameters required to insert a payment.
* Inferred from the InsertPaymentParamsSchema.
*/
export type InsertPaymentParams = z.infer<typeof InsertPaymentParamsSchema>
/**
* Represents the parameters required to insert a FedNow payment.
* Inferred from the InsertFedNowPaymentParamsSchema.
*/
export type InsertFedNowPaymentParams = z.infer<typeof InsertFedNowPaymentParamsSchema>
/**
* Represents the parameters required to insert a ledger entry.
* Inferred from the InsertLedgerEntryParamsSchema.
*/
export type InsertLedgerEntryParams = z.infer<typeof InsertLedgerEntryParamsSchema>
/**
* Represents the parameters required for inserting a promotion ledger entry.
* Inferred from the InsertPromotionLedgerEntryParamsSchema.
*/
export type InsertPromotionLedgerEntryParams = z.infer<typeof InsertPromotionLedgerEntryParamsSchema>
/**
* Represents the parameters required for inserting a transaction record.
* Inferred from the InsertTransactionRecordParamsSchema.
*/
export type InsertTransactionRecordParams = z.infer<typeof InsertTransactionRecordParamsSchema>
/**
* Interface defining the structure of the database operations.
*/
export interface DB {
/**
* Inserts a payment record into the database.
* @param params - The parameters for the payment insertion.
* @returns A promise that resolves with the generated payment ID.
*/
insertPayment: (params: InsertPaymentParams) => Promise<string>
/**
* Inserts a FedNow payment record into the database.
* @param params - The parameters for the FedNow payment insertion.
* @returns A promise that resolves with the generated FedNow payment ID.
*/
insertFedNowPayment: (params: InsertFedNowPaymentParams) => Promise<string>
/**
* Inserts a ledger entry into the database.
* @param params - The parameters for the ledger entry insertion.
* @returns A promise that resolves with the generated ledger ID.
*/
insertLedgerEntry: (params: InsertLedgerEntryParams) => Promise<string>
/**
* Inserts a promotion ledger entry into the database.
* @param params - The parameters for the promotion ledger entry insertion.
* @returns A promise that resolves with the generated promotion ledger ID.
*/
insertPromotionLedgerEntry: (
params: InsertPromotionLedgerEntryParams
) => Promise<string>
/**
* Inserts a transaction record into the database.
* @param params - The parameters for the transaction record insertion.
* @returns A promise that resolves with the generated transaction record ID.
*/
insertTransactionRecord: (
params: InsertTransactionRecordParams
) => Promise<string>
};

src/db/index.ts

/**
* Module dependencies.
*/
import AWS from 'aws-sdk'
import { getEnvVariable, type genId as genIdType, formatDate } from '../helpers'
import { PaymentMethod, PaymentStatus } from '../types'
import {
type InsertPaymentParams,
type InsertFedNowPaymentParams,
type InsertLedgerEntryParams,
type InsertPromotionLedgerEntryParams,
type InsertTransactionRecordParams,
type DB
} from './types'
import { InsertPaymentParamsSchema, InsertFedNowPaymentParamsSchema, InsertLedgerEntryParamsSchema, InsertPromotionLedgerEntryParamsSchema, InsertTransactionRecordParamsSchema } from './schemas'
const RDS = new AWS.RDSDataService()
/**
* Defines the types for the dependencies required by the module.
*/
interface Dependencies {
genId: typeof genIdType
}
/**
* Factory function to create various database operation methods.
* This function initializes methods for different database operations using the provided dependencies.
*
* @param {Dependencies} dependencies - The required dependencies including `genId`.
* @returns An object containing methods for various database operations.
*/
export default ({ genId }: Dependencies): DB => ({
/**
* Inserts a payment record into the database.
* This function takes payment details, validates them against the `InsertPaymentParamsSchema`,
* and then inserts a new record into the payment table.
*
* @param {InsertPaymentParams} params - The parameters for the payment insertion.
* The `params` object includes payerId, payeeId, developerId, amount, interactionTypeId, paymentMethod,
* and sqlTransactionId, which are essential for creating the payment record.
*
* @returns {Promise<string>} A promise that resolves with the generated payment ID.
* The promise resolves after the payment record is successfully inserted into the database.
* If the operation fails, the promise rejects with an error detailing the cause of the failure.
*
* @example
* ```
* const paymentParams: InsertPaymentParams = {
* payerId: '12345',
* payeeId: '67890',
* developerId: '11223',
* amount: 100.50,
* interactionTypeId: 3,
* paymentMethod: PaymentMethod.Card,
* sqlTransactionId: 'abcd1234'
* };
* insertPayment(paymentParams)
* .then(paymentId => console.log(`Payment inserted with ID: ${paymentId}`))
* .catch(error => console.error(`Failed to insert payment: ${error}`));
* ```
*/
insertPayment: async (params: InsertPaymentParams): Promise<string> => {
InsertPaymentParamsSchema.parse(params)
const {
payerId,
payeeId,
developerId,
amount,
interactionTypeId,
paymentMethod,
sqlTransactionId
} = InsertPaymentParamsSchema.parse(params)
const sql = 'INSERT ...'
const paymentId = genId(32)
const statementParams: AWS.RDSDataService.ExecuteStatementRequest = {
database: getEnvVariable('DATABASE'),
secretArn: getEnvVariable('SECRET_ARN'),
resourceArn: getEnvVariable('CLUSTER_ARN'),
transactionId: sqlTransactionId,
sql,
parameters: [
{
name: 'paymentId',
value: { blobValue: Buffer.from(paymentId, 'hex') }
},
{
name: 'payerId',
value: { blobValue: Buffer.from(payerId, 'hex') }
},
{
name: 'payeeId',
value: { blobValue: Buffer.from(payeeId, 'hex') }
},
{
name: 'developerId',
value: { blobValue: Buffer.from(developerId, 'hex') }
},
{
name: 'paymentAmount',
value: { doubleValue: amount }
},
{
name: 'interactionTypeId',
value: { doubleValue: interactionTypeId }
},
{
name: 'paymentMethod',
value: { doubleValue: paymentMethod }
},
{
name: 'paymentStatus',
value: {
doubleValue:
paymentMethod !== PaymentMethod.FedNow || amount === 0 ? PaymentStatus.COMPLETE : PaymentStatus.PENDING
}
},
{
name: 'datePaid',
value: {
stringValue:
paymentMethod === PaymentMethod.FedNow && amount > 0
? undefined
: formatDate(new Date()),
isNull: paymentMethod === PaymentMethod.FedNow && amount > 0
}
}
]
}
await RDS.executeStatement(statementParams).promise()
return paymentId
},
/**
* Inserts a FedNow payment record into the database.
* This function is specific to FedNow payments and takes necessary details,
* validates them, and inserts a record into the FedNow payments table.
*
* @param {InsertFedNowPaymentParams} params - The parameters for the FedNow payment insertion.
* Includes paymentId, payerAccountId, payeeAccountId, and sqlTransactionId.
*
* @returns {Promise<string>} A promise that resolves with the generated FedNow payment ID.
* Resolves after successful insertion of the FedNow payment record.
*
* @example
* ```
* const fedNowParams: InsertFedNowPaymentParams = {
* paymentId: 'payment123',
* payerAccountId: 'account456',
* payeeAccountId: 'account789',
* sqlTransactionId: 'xyz9876'
* };
* insertFedNowPayment(fedNowParams)
* .then(fedNowId => console.log(`FedNow payment inserted with ID: ${fedNowId}`))
* .catch(error => console.error(`Failed to insert FedNow payment: ${error}`));
* ```
*/
insertFedNowPayment: async (params: InsertFedNowPaymentParams): Promise<string> => {
InsertFedNowPaymentParamsSchema.parse(params)
const {
paymentId,
payerAccountId,
payeeAccountId,
sqlTransactionId
} = params
const sql = 'INSERT ...'
const fedNowPaymentId = genId(32)
const statementParams: AWS.RDSDataService.ExecuteStatementRequest = {
database: getEnvVariable('DATABASE'),
secretArn: getEnvVariable('SECRET_ARN'),
resourceArn: getEnvVariable('CLUSTER_ARN'),
transactionId: sqlTransactionId,
sql,
parameters: [
{
name: 'fedNowPaymentId',
value: { blobValue: Buffer.from(fedNowPaymentId, 'hex') }
},
{
name: 'paymentId',
value: { blobValue: Buffer.from(paymentId, 'hex') }
},
{
name: 'payerAccountId',
value: { stringValue: payerAccountId }
},
{
name: 'payeeAccountId',
value: { stringValue: payeeAccountId }
}
]
}
await RDS.executeStatement(statementParams).promise()
return fedNowPaymentId
},
/**
* Inserts a ledger entry into the database.
* This function handles the insertion of a general ledger entry, taking various transaction details.
*
* @param {InsertLedgerEntryParams} params - The parameters for the ledger entry insertion.
* Parameters include payerId, payeeId, developerId, amount, interactionTypeId, and sqlTransactionId.
*
* @returns {Promise<string>} A promise that resolves with the generated ledger ID.
* Resolves after successful insertion of the ledger entry.
*
* @example
* ```
* const ledgerParams: InsertLedgerEntryParams = {
* payerId: '123abc',
* payeeId: '456def',
* developerId: '789ghi',
* amount: 150.75,
* interactionTypeId: 4,
* sqlTransactionId: 'tran12345'
* };
* insertLedgerEntry(ledgerParams)
* .then(ledgerId => console.log(`Ledger entry inserted with ID: ${ledgerId}`))
* .catch(error => console.error(`Failed to insert ledger entry: ${error}`));
* ```
*/
insertLedgerEntry: async (params: InsertLedgerEntryParams): Promise<string> => {
const {
payerId,
payeeId,
developerId,
amount,
interactionTypeId,
sqlTransactionId
} = params
InsertLedgerEntryParamsSchema.parse(params)
const sql = 'INSERT ...'
const ledgerId = genId(32)
const statementParams: AWS.RDSDataService.ExecuteStatementRequest = {
database: getEnvVariable('DATABASE'),
secretArn: getEnvVariable('SECRET_ARN'),
resourceArn: getEnvVariable('CLUSTER_ARN'),
transactionId: sqlTransactionId,
sql,
parameters: [
{
name: 'ledgerId',
value: { blobValue: Buffer.from(ledgerId, 'hex') }
},
{
name: 'payerId',
value: { blobValue: Buffer.from(payerId, 'hex') }
},
{
name: 'payeeId',
value: { blobValue: Buffer.from(payeeId, 'hex') }
},
{
name: 'amount',
value: { doubleValue: amount }
},
{
name: 'interactionTypeId',
value: { doubleValue: interactionTypeId }
},
{
name: 'developerId',
value: { blobValue: Buffer.from(developerId, 'hex') }
}
]
}
await RDS.executeStatement(statementParams).promise()
return ledgerId
},
/**
* Inserts a promotion ledger entry into the database.
* This function is for recording promotional transactions, taking details like promotion amount.
*
* @param {InsertPromotionLedgerEntryParams} params - The parameters for the promotion ledger entry insertion.
* Includes developerId, payeeId, payerId, promoAmount, interactionTypeId, and sqlTransactionId.
*
* @returns {Promise<string>} A promise that resolves with the generated promotion ledger ID.
* Resolves after successful insertion of the promotion ledger entry.
*
* @example
* ```
* const promoLedgerParams: InsertPromotionLedgerEntryParams = {
* developerId: 'dev123',
* payeeId: 'payee456',
* payerId: 'payer789',
* promoAmount: 25.00,
* interactionTypeId: 5,
* sqlTransactionId: 'sqltrans678'
* };
* insertPromotionLedgerEntry(promoLedgerParams)
* .then(promoLedgerId => console.log(`Promotion ledger entry inserted with ID: ${promoLedgerId}`))
* .catch(error => console.error(`Failed to insert promotion ledger entry: ${error}`));
* ```
*/
insertPromotionLedgerEntry: async (params: InsertPromotionLedgerEntryParams): Promise<string> => {
InsertPromotionLedgerEntryParamsSchema.parse(params)
const {
developerId,
payeeId,
payerId,
promoAmount,
interactionTypeId,
sqlTransactionId
} = params
const sql = 'INSERT ...'
const ledgerId = genId(32)
const statementParams: AWS.RDSDataService.ExecuteStatementRequest = {
database: getEnvVariable('DATABASE'),
secretArn: getEnvVariable('SECRET_ARN'),
resourceArn: getEnvVariable('CLUSTER_ARN'),
transactionId: sqlTransactionId,
sql,
parameters: [
{
name: 'ledgerId',
value: { blobValue: Buffer.from(ledgerId, 'hex') }
},
{
name: 'payerId',
value: { blobValue: Buffer.from(payerId, 'hex') }
},
{
name: 'payeeId',
value: { blobValue: Buffer.from(payeeId, 'hex') }
},
{
name: 'developerId',
value: { blobValue: Buffer.from(developerId, 'hex') }
},
{
name: 'amount',
value: { doubleValue: promoAmount }
},
{
name: 'interactionTypeId',
value: { doubleValue: interactionTypeId }
}
]
}
await RDS.executeStatement(statementParams).promise()
return ledgerId
},
/**
* Inserts a transaction record into the database.
* This function manages the insertion of a comprehensive transaction record, including multiple ledger entries.
*
* @param {InsertTransactionRecordParams} params - The parameters for the transaction record insertion.
* Includes a list of ledgerEntries and an sqlTransactionId.
*
* @returns {Promise<string>} A promise that resolves with the generated transaction record ID.
* Resolves after successful insertion of the transaction record.
*
* @example
* ```
* const transactionRecordParams: InsertTransactionRecordParams = {
* ledgerEntries: ['ledger123', 'ledger456'],
* sqlTransactionId: 'transql789'
* };
* insertTransactionRecord(transactionRecordParams)
* .then(transactionId => console.log(`Transaction record inserted with ID: ${transactionId}`))
* .catch(error => console.error(`Failed to insert transaction record: ${error}`));
* ```
*/
insertTransactionRecord: async (params: InsertTransactionRecordParams): Promise<string> => {
InsertTransactionRecordParamsSchema.parse(params)
const {
ledgerEntries,
sqlTransactionId
} = params
const sql = 'INSERT ...'
const pursTransactionId = genId(32)
const parameterSets = ledgerEntries.map((ledgerEntry) => [
{
name: 'transactionId',
value: { blobValue: Buffer.from(pursTransactionId, 'hex') }
},
{
name: 'ledgerId',
value: { blobValue: Buffer.from(ledgerEntry, 'hex') }
}
])
const statementParams: AWS.RDSDataService.BatchExecuteStatementRequest = {
database: getEnvVariable('DATABASE'),
secretArn: getEnvVariable('SECRET_ARN'),
resourceArn: getEnvVariable('CLUSTER_ARN'),
transactionId: sqlTransactionId,
sql,
parameterSets
}
await RDS.batchExecuteStatement(statementParams).promise()
return pursTransactionId
}
})

src/helpers.ts

/**
* Retrieves the value of an environment variable.
* This function looks up an environment variable by its name and returns its value.
* If the environment variable is not set, it throws an error.
*
* @param {string} name - The name of the environment variable to retrieve.
* @returns {string} The value of the environment variable.
* @throws {Error} If the environment variable is not set.
*
* @example
* ```
* try {
* const databaseUrl = getEnvVariable('DATABASE_URL');
* console.log(databaseUrl);
* } catch (error) {
* console.error(error.message);
* }
* ```
*/
export const getEnvVariable = (name: string): string => {
const value = process.env[name]
if (value == null) {
throw new Error(`Environment variable ${name} not set`)
}
return value
}
/**
* Generates a random hexadecimal string of a specified length.
* This function creates a string composed of random hexadecimal digits.
* The length of the generated string is determined by the input parameter.
*
* @param {number} length - The length of the hexadecimal string to generate.
* @returns {string} A random hexadecimal string of the specified length.
*
* @example
* ```
* const randomId = genId(16);
* console.log(randomId); // Outputs a 16-character hexadecimal string.
* ```
*/
export const genId = (length: number): string => {
let result = ''
for (let i = 0; i < length; i++) {
// Generate a random number between 0 and 15, then convert it to a hexadecimal string
const randomHexDigit = Math.floor(Math.random() * 16).toString(16)
result += randomHexDigit
}
return result
}
/**
* Formats a Date object into a string.
* This function converts a Date object into a string in the format 'YYYY-MM-DD HH:MM:SS'.
* The time is formatted to the local timezone.
*
* @param {Date} date - The Date object to format.
* @returns {string} The formatted date string.
*
* @example
* ```
* const currentDate = new Date();
* const formattedDate = formatDate(currentDate);
* console.log(formattedDate); // Outputs the current date and time in 'YYYY-MM-DD HH:MM:SS' format.
* ```
*/
export const formatDate = (date: Date): string => {
return new Date().toISOString().slice(0, 19).replace('T', ' ')
}