Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "No url defined in config file" when using ESM #454

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions lib/env/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ function getConfigPath() {
return path.join(process.cwd(), fileOptionValue);
}

function getModuleExports(module) {
// If ESM module format need to return default export
return module.default ? module.default : module;
}

module.exports = {
DEFAULT_CONFIG_FILE_NAME,

Expand Down Expand Up @@ -63,11 +68,12 @@ module.exports = {
}
const configPath = getConfigPath();
try {
return await Promise.resolve(moduleLoader.require(configPath));
const result = await moduleLoader.require(configPath);
return getModuleExports(result);
} catch (e) {
if (e.code === 'ERR_REQUIRE_ESM') {
const loadedImport = await moduleLoader.import(url.pathToFileURL(configPath));
return loadedImport.default
return getModuleExports(loadedImport);
}
throw e;
}
Expand Down
30 changes: 30 additions & 0 deletions test/env/config.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,5 +142,35 @@ describe("config", () => {
await config.read();
expect(moduleLoader.import.called).to.equal(true);
});

it("should handle ESM modules with default export", async () => {
const expectedConfig = {
mongodb: {
url: 'mongodb://localhost:27017',
databaseName: 'test'
}
};

moduleLoader.require = sinon.stub().resolves({
default: expectedConfig
});

const actual = await config.read();
expect(actual).to.deep.equal(expectedConfig);
});

it("should handle regular CommonJS modules", async () => {
const expectedConfig = {
mongodb: {
url: 'mongodb://localhost:27017',
databaseName: 'test'
}
};

moduleLoader.require = sinon.stub().resolves(expectedConfig);

const actual = await config.read();
expect(actual).to.deep.equal(expectedConfig);
});
});
});