Skip to content

Commit

Permalink
chore: updated deps and used non-sync fs
Browse files Browse the repository at this point in the history
  • Loading branch information
Sayan751 committed Jul 23, 2024
1 parent 787521e commit f9cc886
Show file tree
Hide file tree
Showing 8 changed files with 360 additions and 273 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,5 @@ typings/

# next.js build output
.next

.ignored
45 changes: 37 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,55 @@ const loaderName = 'app-settings-loader';
const schema = { env: 'string' };
const defaultOptions = { env: "development" };

const parseFileContent = (content, filePath) => {
function parseFileContent(content, filePath) {
try {
return JSON.parse(content);
} catch (e) {
throw new Error(`Unable to parse the file ${filePath}; ${loaderName} can only be used to load and transform well-formed json files.`);
}
}

/**
* Merges source with envOverride.
* @param {(err: Error| null, content?: string) => void} source content
* @param {string} source content
* @param {string} sourcePath path to the source configuration file
* @param {string|undefined|null} envOverride content
* @param {string|undefined|null} envOverridePath path to the environment-specific configuration file
*/
function merge(callback, source, sourcePath, envOverride, envOverridePath) {
try {
const sourceConfig = parseFileContent(source, sourcePath);
const envConfig = envOverridePath != null ? parseFileContent(envOverride, envOverridePath) : {};
callback(null, JSON.stringify(sealedMerge(sourceConfig, envConfig)));
} catch (e) {
callback(e);
}
}


module.exports = function (source) {
const callback = this.async();

const options = Object.assign(defaultOptions, this.getOptions());
validate(schema, options, loaderName);
validate(schema, options, loaderName);

const ext = path.extname(this.resourcePath);
const envFile = path.join(path.dirname(this.resourcePath), `${path.basename(this.resourcePath, ext)}.${options.env}${ext}`);
let envConfig = {};
fs.access(envFile, fs.constants.R_OK, (err) => {
if (err) {
merge(callback, source, this.sourcePath);
return;
}

if (fs.existsSync(envFile)) {
envConfig = parseFileContent(fs.readFileSync(envFile), envFile);
}
const sourceConfig = parseFileContent(source, this.resourcePath);
this.addDependency(envFile);
fs.readFile(envFile, (err, content) => {
if (err) {
callback(err);
return;
}

return JSON.stringify(sealedMerge(sourceConfig, envConfig));
merge(callback, source, this.sourcePath, content, envFile);
});
});
};
Loading

0 comments on commit f9cc886

Please # to comment.