Skip to content

Instantly share code, notes, and snippets.

@k9ert
Last active March 5, 2024 12:28
Show Gist options
  • Save k9ert/3edcf1205a283030786109394eaacc1a to your computer and use it in GitHub Desktop.
Save k9ert/3edcf1205a283030786109394eaacc1a to your computer and use it in GitHub Desktop.
Dynamically loading functions from files in a directory and exposing them via a variable
import {readdirSync} from 'fs'
import path from 'path'
export const logAPICall = async <T>(
apiFunction: () => Promise<T>,
functionName: string,
): Promise<T> => {
try {
const result = await apiFunction()
logger.error(
`API call successful for ${functionName}. Result: ${JSON.stringify(
result,
)}`,
)
return result
} catch (error) {
logger.error(`Error occurred while calling ${functionName}: ${error}`)
throw error
}
}
const apiDirectory = path.join(__dirname, 'api')
const apiFiles = readdirSync(apiDirectory).filter(
file => file.endsWith('.ts') && file !== 'index.ts',
)
const modifiedAPI: Record<string, any> = {}
apiFiles.forEach(file => {
const apiModule = require(path.join(apiDirectory, file))
Object.keys(apiModule).forEach(key => {
const apiFunction = apiModule[key]
if (typeof apiFunction === 'function') {
const functionName = `${file.replace('.ts', '')}.${key}`
modifiedAPI[key] = async (...args: any[]) => {
return logAPICall(() => apiFunction(...args), functionName)
}
}
})
})
export const api = {...modifiedAPI}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment