dynamicl
Version:
A library for auto-detecting and loading classes
55 lines (54 loc) • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Detectable = void 0;
exports.autodetect = autodetect;
require("reflect-metadata");
const fs = require("fs");
const path = require("path");
class Detectable {
constructor(name) {
this.name = name;
}
}
exports.Detectable = Detectable;
function autodetect(options) {
return function (target, propertyKey) {
const location = path.resolve(options.location);
Reflect.defineMetadata('autodetect:options', options, target, propertyKey);
Object.defineProperty(target, propertyKey, {
get: function () {
if (!this._loadedItems) {
this._loadedItems = loadItems(location, options.baseClass);
}
return this._loadedItems;
},
configurable: true,
enumerable: true
});
};
}
function loadItems(directoryPath, BaseClass) {
const items = [];
const files = fs.readdirSync(directoryPath);
for (const file of files) {
if (file.endsWith('.ts') || file.endsWith('.js')) {
const filePath = path.join(directoryPath, file);
let module;
try {
module = require(filePath);
}
catch (error) {
console.error(`Error loading module ${filePath}:`, error);
continue;
}
for (const exportedItem of Object.values(module)) {
if (typeof exportedItem === 'function' &&
exportedItem.prototype instanceof BaseClass) {
const ItemClass = exportedItem;
items.push(new ItemClass(path.basename(file, path.extname(file))));
}
}
}
}
return items;
}