Here is a function that requires 2 arguments: a mandatory tableName
and an optional connectionName
:
export const clearTable = async (
tableName: string[],
connectionName = 'default'
) => {
try {
const connection = getConnection(connectionName)
const promises = tableName.map((table) =>
connection.query(`DELETE FROM ${table}`)
)
await Promise.all(promises)
} catch (error) {
throw new Error(
`Failed to clear table '${tableName}' on database '${connectionName}': ${error}`
)
}
}
To use this function, you can call it like this:
clearTable(['table1', 'table2']) // works fine with an array
clearTable('table3') // fails because it's not an array > TypeError: tableName.map is not a function
If you need to convert a single string
to an array of strings in order to use the same logic with array.map
, one suggestion is to explore the possibility of utilizing rest parameters. However, be aware that a rest parameter can be zero or more, while we require at least one argument.
How would you handle this scenario efficiently?