UNPKG

@node-in-layers/core

Version:

The core library for the Node In Layers rapid web development framework.

89 lines 3.26 kB
import merge from 'lodash/merge.js'; import { v4 } from 'uuid'; import get from 'lodash/get.js'; import { isConfig, validateConfig } from '../libs.js'; import { CoreNamespace, } from '../types.js'; import { memoizeValue } from '../utils.js'; import { standardLogger } from './logging.js'; const name = CoreNamespace.globals; const services = { create: ({ environment, workingDirectory, runtimeId, }) => { const getRootLogger = standardLogger; const _findConfigPath = async () => { const nodeFS = await import('node:fs'); const nodePath = await import('node:path'); const extensions = ['mjs', 'js', 'mts', 'ts']; return extensions .map(e => { return nodePath.resolve(`${workingDirectory}/config.${environment}.${e}`); }) .find(filePath => { return nodeFS.existsSync(filePath); }); }; const _loadConfig = memoizeValue(async () => { process.chdir(workingDirectory); const fullPath = await _findConfigPath(); if (!fullPath) { throw new Error(`Could not find a config.${environment} for mts, ts, mjs, or js.`); } const url = new URL(`file://${fullPath}`); // @ts-ignore const module = await import(url); const func = module.default ? module.default : module; const config = await func(); validateConfig(config); return config; }); const loadConfig = () => _loadConfig(); const getConstants = () => { return { runtimeId: runtimeId || v4(), workingDirectory, environment, }; }; const getGlobals = (commonGlobals, app) => { if (app.globals) { return app.globals.create(commonGlobals); } return Promise.resolve({}); }; return { loadConfig, getConstants, getRootLogger, getGlobals, }; }, }; const features = { create: (context) => { const ourServices = get(context.services, name); if (!ourServices) { throw new Error(`Services for ${name} not found`); } const loadGlobals = async (environmentOrConfig) => { const config = await (isConfig(environmentOrConfig) ? environmentOrConfig : ourServices.loadConfig()); validateConfig(config); const commonGlobals = { config, rootLogger: ourServices.getRootLogger(), constants: ourServices.getConstants(), }; const globals = await config[CoreNamespace.root].apps.reduce(async (accP, app) => { const acc = await accP; const dep = await ourServices.getGlobals(commonGlobals, app); return merge(acc, dep); }, Promise.resolve({})); return merge(commonGlobals, globals); }; return { loadGlobals, }; }, }; export { services, features, name }; //# sourceMappingURL=index.js.map