From 491aa11ac520c68246f37a58ec83032dbab0c72e Mon Sep 17 00:00:00 2001 From: Kir_Antipov Date: Sat, 14 Jan 2023 13:38:15 +0000 Subject: [PATCH] Made `ModuleLoader` interface And added 2 default implementations: - `NODE_MODULE_LOADER` - uses `import` under the hood - `DYNAMIC_MODULE_LOADER` - will be able to load modules needed in other parts of this project. Currently it's just a stub --- src/utils/reflection/module-loader.g.ts | 3 +++ src/utils/reflection/module-loader.ts | 25 +++++++++++++++++++ .../utils/reflection/module-loader.spec.ts | 17 +++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 src/utils/reflection/module-loader.g.ts create mode 100644 src/utils/reflection/module-loader.ts create mode 100644 tests/unit/utils/reflection/module-loader.spec.ts diff --git a/src/utils/reflection/module-loader.g.ts b/src/utils/reflection/module-loader.g.ts new file mode 100644 index 0000000..21b63a7 --- /dev/null +++ b/src/utils/reflection/module-loader.g.ts @@ -0,0 +1,3 @@ +export const ACTION_MODULE_LOADER = (path: string): Promise> => { + return Promise.resolve(undefined); +}; diff --git a/src/utils/reflection/module-loader.ts b/src/utils/reflection/module-loader.ts new file mode 100644 index 0000000..ee02c67 --- /dev/null +++ b/src/utils/reflection/module-loader.ts @@ -0,0 +1,25 @@ +import { ACTION_MODULE_LOADER } from "./module-loader.g"; + +/** + * Represents a function that loads a module by its name. + */ +export interface ModuleLoader { + /** + * Loads a module by its name. + * + * @param name - The name of the module to load. + * + * @returns A promise that resolves with the loaded module. + */ + (name: string): Promise; +} + +/** + * A module loader implementation that loads modules using Node.js dynamic `import` syntax. + */ +export const NODE_MODULE_LOADER: ModuleLoader = new Function("x", "return import(x).catch(() => undefined)") as (name: string) => Promise; + +/** + * Represents a dynamic module loader that is capable of loading modules by their source path (e.g., `"utils/string-utils"`). + */ +export const DYNAMIC_MODULE_LOADER: ModuleLoader = ACTION_MODULE_LOADER; diff --git a/tests/unit/utils/reflection/module-loader.spec.ts b/tests/unit/utils/reflection/module-loader.spec.ts new file mode 100644 index 0000000..f849b4d --- /dev/null +++ b/tests/unit/utils/reflection/module-loader.spec.ts @@ -0,0 +1,17 @@ +import { NODE_MODULE_LOADER, DYNAMIC_MODULE_LOADER } from "@/utils/reflection/module-loader"; + +describe("NODE_MODULE_LOADER", () => { + test("returns undefined if a module cannot be loaded", async () => { + const loadedModule = await NODE_MODULE_LOADER("#"); + + expect(loadedModule).toBeUndefined(); + }); +}); + +describe("DYNAMIC_MODULE_LOADER", () => { + test("returns undefined if a module cannot be loaded", async () => { + const loadedModule = await DYNAMIC_MODULE_LOADER("#"); + + expect(loadedModule).toBeUndefined(); + }); +});