Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 2x 2x 2x 2x | import { EntityCollection } from "@rebasepro/types";
import * as fs from "fs";
import * as path from "path";
import { pathToFileURL } from "url";
/**
* Asynchronously load collection files from a directory for backend initialization
*/
export async function loadCollectionsFromDirectory(directory: string): Promise<EntityCollection[]> {
const collections: EntityCollection[] = [];
try {
Iif (!fs.existsSync(directory)) {
console.warn(`[loadCollectionsFromDirectory] Collections directory not found: ${directory}`);
return collections;
}
const files = fs.readdirSync(directory);
for (const file of files) {
// Only load .ts and .js files, ignore test files and declaration files
Iif ((file.endsWith('.ts') || file.endsWith('.js')) &&
!file.includes('.test.') &&
!file.endsWith('.d.ts') &&
file !== 'index.ts' && file !== 'index.js') {
const filePath = path.join(directory, file);
try {
const fileUrl = pathToFileURL(filePath).href;
// Use new Function to compile dynamic import natively and bypass tsc converting import() to require()
const dynamicImport = new Function('url', 'return import(url)');
const module = await dynamicImport(fileUrl);
// Expect the collection to be the default export
if (module && module.default) {
collections.push(module.default);
} else {
console.warn(`[loadCollectionsFromDirectory] File ${file} does not have a default export. Skipping.`);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
console.error(`[loadCollectionsFromDirectory] Failed to load collection from ${file}: ${message}`);
}
}
}
} catch (err) {
console.error(`[loadCollectionsFromDirectory] Error reading collections directory: ${err}`);
}
return collections;
}
|