diff --git a/lib/cloudinary-proxy.js b/lib/cloudinary-proxy.js index 2b2ecab..0ea9c15 100644 --- a/lib/cloudinary-proxy.js +++ b/lib/cloudinary-proxy.js @@ -7,9 +7,10 @@ */ const _has = require("lodash/has"); const cloudinary = require("cloudinary-core"); +const requireConfig = require("./helpers/requireConfig"); // https://cloudinary.com/documentation/solution_overview#configuration_parameters -const runConfig = require(`${process.env.INIT_CWD}/cloudinaryrc.json`); +const runConfig = requireConfig(); if (!_has(runConfig, "native.cloud_name")) { throw new Error("You need to provide a **native** object with the mandatory **cloud_name** field"); diff --git a/lib/helpers/requireConfig.js b/lib/helpers/requireConfig.js new file mode 100644 index 0000000..128041d --- /dev/null +++ b/lib/helpers/requireConfig.js @@ -0,0 +1,19 @@ +/** + * Load the cloudinaryrc configuration from the top level path + * @throws Will throw if the file is not or the error faced during the `require` call + * @returns {NodeRequire} JSON configuration module + */ +function requireConfig() { + const configFileLocation = `${process.env.INIT_CWD || process.cwd()}/cloudinaryrc.json`; + + try { + return require(configFileLocation); + } catch (e) { + if (e.code !== "MODULE_NOT_FOUND") { + throw e; + } + throw Error(`Cloudinary config could not be found at ${configFileLocation}`); + } +} + +module.exports = requireConfig; diff --git a/test/requireConfig.spec.js b/test/requireConfig.spec.js new file mode 100644 index 0000000..5bb9df4 --- /dev/null +++ b/test/requireConfig.spec.js @@ -0,0 +1,25 @@ +const requireConfig = require("../lib/helpers/requireConfig"); + +describe("requireConfig", () => { + it("throws when config not found at expected location", () => { + expect(requireConfig).toThrow(`Cloudinary config could not be found at ${process.env.INIT_CWD || process.cwd()}`); + }); + + it("loads the required file", () => { + const mockConfig = JSON.stringify({ test: 1 }); + + jest.mock( + `${process.cwd()}/cloudinaryrc.json`, + () => { + return mockConfig; + }, + { virtual: true } + ); + + const loadedConfig = requireConfig(); + + expect(loadedConfig).toBe(mockConfig); + }); + + afterAll(() => jest.resetAllMocks()); +});