Skip to content

Commit

Permalink
fix(core): use createRequire instead of dynamic import for JSON files
Browse files Browse the repository at this point in the history
Closes #2738
  • Loading branch information
B4nan committed Feb 10, 2022
1 parent c19963e commit f567d2d
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 19 deletions.
2 changes: 1 addition & 1 deletion packages/cli/src/CLIHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class CLIHelper {

static async getModuleVersion(name: string): Promise<string> {
try {
const pkg = Utils.requireFrom(`${name}/package.json`, process.cwd());
const pkg = Utils.requireFrom<{ version: string }>(`${name}/package.json`, process.cwd());
return colors.green(pkg.version);
} catch {
return colors.red('not-found');
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/MikroORM.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ export class MikroORM<D extends IDatabaseDriver = IDatabaseDriver> {
* If you omit the `options` parameter, your CLI config will be used.
*/
static async init<D extends IDatabaseDriver = IDatabaseDriver>(options?: Options<D> | Configuration<D>, connect = true): Promise<MikroORM<D>> {
ConfigurationLoader.registerDotenv(options);
const coreVersion = await ConfigurationLoader.checkPackageVersion();
const env = ConfigurationLoader.loadEnvironmentVars<D>(options);
const env = ConfigurationLoader.loadEnvironmentVars<D>();

if (!options) {
options = await ConfigurationLoader.getConfiguration<D>();
Expand Down
12 changes: 8 additions & 4 deletions packages/core/src/utils/ConfigurationLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ import { colors } from '../logging/colors';
export class ConfigurationLoader {

static async getConfiguration<D extends IDatabaseDriver = IDatabaseDriver>(validate = true, options?: Partial<Options>): Promise<Configuration<D>> {
const paths = await ConfigurationLoader.getConfigPaths();
const env = ConfigurationLoader.loadEnvironmentVars(options);
this.registerDotenv(options);
const paths = await this.getConfigPaths();
const env = this.loadEnvironmentVars();

for (let path of paths) {
path = Utils.absolutePath(path);
Expand Down Expand Up @@ -120,10 +121,13 @@ export class ConfigurationLoader {
}
}

static loadEnvironmentVars<D extends IDatabaseDriver>(options?: Options<D> | Configuration<D>): Partial<Options<D>> {
static registerDotenv<D extends IDatabaseDriver>(options?: Options<D> | Configuration<D>): void {
const baseDir = options instanceof Configuration ? options.get('baseDir') : options?.baseDir;
const path = process.env.MIKRO_ORM_ENV ?? ((baseDir ?? process.cwd()) + '/.env');
dotenv.config({ path });
}

static loadEnvironmentVars<D extends IDatabaseDriver>(): Partial<Options<D>> {
const ret: Dictionary = {};
const array = (v: string) => v.split(',').map(vv => vv.trim());
const bool = (v: string) => ['true', 't', '1'].includes(v.toLowerCase());
Expand Down Expand Up @@ -211,7 +215,7 @@ export class ConfigurationLoader {
static async getORMPackageVersion(name: string): Promise<string | undefined> {
/* istanbul ignore next */
try {
const pkg = await Utils.dynamicImport<{ version?: string }>(`${name}/package.json`);
const pkg = Utils.requireFrom(`${name}/package.json`, process.cwd());
return pkg?.version;
} catch (e) {
return undefined;
Expand Down
14 changes: 6 additions & 8 deletions packages/core/src/utils/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { pathExists } from 'fs-extra';
import { createHash } from 'crypto';
import { recovery } from 'escaya';
import type { AnyEntity, Dictionary, EntityData, EntityDictionary, EntityMetadata, EntityName, EntityProperty, IMetadataStorage, Primary } from '../typings';
import { GroupOperator, QueryOperator, ReferenceType, PlainObject } from '../enums';
import { GroupOperator, PlainObject, QueryOperator, ReferenceType } from '../enums';
import type { Collection } from '../entity';
import type { Platform } from '../platforms';

Expand Down Expand Up @@ -785,7 +785,7 @@ export class Utils {
* @param id The module to require
* @param from Location to start the node resolution
*/
static requireFrom(id: string, from: string) {
static requireFrom<T extends Dictionary>(id: string, from: string): T {
if (!extname(from)) {
from = join(from, '__fake.js');
}
Expand All @@ -812,16 +812,14 @@ export class Utils {
return Function(`return import('${id}')`)();
}

static async getORMVersion(): Promise<string> {
static getORMVersion(): string {
/* istanbul ignore next */
try {
// this works with ts-node during development (where we have `src` folder)
const pkg = await this.dynamicImport(__dirname + '/../../package.json');
return pkg.version;
return this.requireFrom<{ version: string }>(`../../package.json`, __dirname).version;
} catch {
// this works with node in production build (where we do not have the `src` folder)
const pkg = await this.dynamicImport(__dirname + '/../package.json');
return pkg.version;
return this.requireFrom<{ version: string }>(`../package.json`, __dirname).version;
}
}

Expand Down Expand Up @@ -973,7 +971,7 @@ export class Utils {
from ??= process.cwd();

try {
return Utils.requireFrom(module, from);
return Utils.requireFrom<T>(module, from);
} catch (err: any) {
if (err.message.includes(allowError)) {
// eslint-disable-next-line no-console
Expand Down
8 changes: 8 additions & 0 deletions tests/EntityHelper.mongo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ describe('EntityHelperMongo', () => {
god.name = '123';
expect(wrap(god, true).__touched).toBe(true);
expect(god.isTouched()).toBe(true);
expect(god.toPOJO()).toMatchObject({
name: '123',
email: 'hello@heaven.god',
books: [],
foo: 'bar',
friends: [],
termsAccepted: false,
});
});

test('#load() should populate the entity', async () => {
Expand Down
18 changes: 13 additions & 5 deletions tests/features/cli/CLIHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,20 @@ describe('CLIHelper', () => {
},
};
});
requireFromMock
.mockImplementationOnce(() => ({ register: registerMock }))
.mockImplementationOnce(() => ({ register: registerPathsMock }));
requireFromMock.mockImplementation(id => {
if (id === 'ts-node') {
return { register: registerMock };
}

if (id === 'tsconfig-paths') {
return { register: registerPathsMock };
}

return {};
});
const cli = await CLIConfigurator.configure() as any;
expect(cli.$0).toBe('mikro-orm');
expect(requireFromMock).toHaveBeenCalledTimes(2);
expect(requireFromMock).toHaveBeenCalledTimes(4);
expect(requireFromMock).toHaveBeenCalledWith('ts-node', process.cwd() + '/tsconfig.extended-abs.json');
expect(requireFromMock).toHaveBeenCalledWith('tsconfig-paths', process.cwd() + '/tsconfig.extended-abs.json');
expect(registerPathsMock).toHaveBeenCalledWith({
Expand Down Expand Up @@ -138,7 +146,7 @@ describe('CLIHelper', () => {
const spy = jest.spyOn(ConfigurationLoader, 'getORMPackages');
spy.mockResolvedValueOnce(new Set(['@mikro-orm/weird-package']));
const spy3 = jest.spyOn(Utils, 'getORMVersion');
spy3.mockResolvedValue('5.0.0');
spy3.mockReturnValue('5.0.0');

await expect(ConfigurationLoader.checkPackageVersion()).resolves.toMatch(/^\d+\.\d+\.\d+/);

Expand Down

0 comments on commit f567d2d

Please sign in to comment.