The function below takes 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}`
)
}
}
Calling this function:
clearTable(['table1', 'table2']) // works fine because it receives an array
clearTable('table3') // fails because it's not an array > TypeError: tableName.map is not a function
In one way or another it should be possible to convert a single string to an array of strings to be able to use the same logic with array.map. We've also looked at the REST parameter as suggested here but that seems to be not possible as a rest parameter can be zero or more and we need at least one.
What is the correct way to handle this situation?
tableName: string | string[]?mapfunction wont work ontablenameliketablename.map().typeof tableNamebefore deciding if it should be treated like a string or an array of strings.[tableName]if it's not already an array.