@speedy/json-extends
Version:
Extend a JSON file with one or many existing files.
79 lines (78 loc) • 2.95 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const fs = require("fs");
const path_1 = require("path");
var json;
(function (json) {
/**
* Retrieve a JSON file asynchronous. Supports `extends` with one or many existing JSON files.
*
* @template T
* @param {string} filePath path to a JSON file.
* @param {{ [id: string]: string }} [namedExtends] A key value pair of named extends paths.
*
* @example
* import { json } from "@speedy/json-extends";
*
* const named = {
* "@speedy/commit-msg-hook:latest": "./node_modules/config/config.json"
* };
*
* json.read("local-config.json", named)
* .then(content => {
* // json content
* });
*
* @returns {Promise<T>}
*/
function read(filePath, namedExtends) {
return __awaiter(this, void 0, void 0, function* () {
return readSync(filePath, namedExtends);
});
}
json.read = read;
/**
* Retrieve a JSON file synchronously. Supports `extends` with one or many existing JSON files.
*
* @template T
* @param {string} filePath path to a JSON file.
* @param {{ [id: string]: string }} [namedExtends] A key value pair of named extends paths.
*
* @example
* import { json } from "@speedy/json-extends";
*
* const named = {
* "@speedy/commit-msg-hook:latest": "./node_modules/config/config.json"
* };
*
* const content = json.readSync("local-config.json", named);
*
* @returns {T}
*/
function readSync(filePath, namedExtends) {
const content = JSON.parse(fs.readFileSync(filePath, "utf-8"));
if (_.isEmpty(content.extends)) {
return content;
}
const contentUnmerged = [];
for (let path of _.castArray(content.extends)) {
if (namedExtends) {
const extendsValue = namedExtends[path];
if (extendsValue) {
path = extendsValue;
}
}
contentUnmerged.push(readSync(path_1.resolve(path_1.dirname(filePath), path), namedExtends));
}
return _.merge({}, ...contentUnmerged, content);
}
json.readSync = readSync;
})(json = exports.json || (exports.json = {}));