smappy
Version:
A lightweight, profile-based mapping library for NestJS.
60 lines (59 loc) • 2.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MapperModule = void 0;
const common_1 = require("@nestjs/common");
const fast_glob_1 = require("fast-glob");
const decorator_1 = require("./decorator");
class MapperModule {
static logger = new common_1.Logger(MapperModule.name);
static forRoot({ paths = [], profiles = [], isGlobal = false, }) {
const scanned = this.scanAndImportMappers(paths);
this.verifyProfiles(profiles);
const allProviders = [...profiles, ...scanned];
if (allProviders.length === 0)
this.logger.warn("No mappers found");
return {
global: isGlobal,
module: MapperModule,
providers: [...profiles, ...scanned],
exports: [...profiles, ...scanned],
};
}
static async forRootAsync(options) {
const opts = await options.useFactory(...(options.inject || []));
this.verifyProfiles(opts.profiles || []);
const scanned = opts.paths?.length
? MapperModule.scanAndImportMappers(opts.paths)
: [];
const providers = [...(opts.profiles || []), ...scanned];
if (providers.length === 0)
this.logger.warn("No mappers found");
return {
global: opts.isGlobal,
module: MapperModule,
providers,
exports: providers,
};
}
static scanAndImportMappers = (paths) => {
const mappers = [];
const normalizedPaths = paths.map((path) => path.replace(/\\/g, "/"));
const files = (0, fast_glob_1.sync)(normalizedPaths, { onlyFiles: true });
for (const file of files) {
const module = require(file);
for (const exported of Object.values(module)) {
if (typeof exported === "function" && (0, decorator_1.isMapper)(exported)) {
mappers.push(exported);
}
}
}
return mappers;
};
static verifyProfiles(profiles) {
return profiles.map((profile) => {
if (!(0, decorator_1.isMapper)(profile))
throw new Error(`Mapper ${profile.name} is not decorated with @Mapper()`);
});
}
}
exports.MapperModule = MapperModule;