-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathsafeImport.ts
More file actions
24 lines (21 loc) · 926 Bytes
/
safeImport.ts
File metadata and controls
24 lines (21 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/**
* Safely require path, fall back to fallback if module cannot load
* @param {string} path Path to attempt to load
* @param {Object} fallback fallback response if error or no module
* @returns {Promise<any>} module or the default object
*/
export const safeImport = async <T extends object>(path: string, fallback: T = {} as T): Promise<T> => {
try {
const mod: T | { default: T } = path.includes('.json')
? await import(path, { with: { type: 'json' } })
: await import(path);
return 'default' in mod ? (mod as { default: T }).default : (mod as T);
} catch (error) {
if ((process.env.LOG_LEVEL || 'ERROR').toUpperCase() === 'DEBUG') {
console.debug(`Failed to load module at ${path} ... returning fallback`);
}
return fallback;
}
};