nginx-testing
Version:
Support for integration/acceptance testing of nginx configuration.
99 lines • 3.14 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseConf = void 0;
const assert_1 = require("assert");
const nginx_conf_1 = require("nginx-conf");
/**
* Parses the given nginx config.
*/
function parseConf(source) {
let result;
// XXX: This function is actually synchronous, just silly API...
nginx_conf_1.NginxConfFile.createFromSource(source, { tab: ' ' }, (err, conf) => {
if (err)
throw err;
result = conf;
});
(0, assert_1.strict)(result, 'This should not have happened');
return nginxConfEditor(result);
}
exports.parseConf = parseConf;
const nginxConfEditor = (conf) => ({
get(path) {
const item = get(conf.nginx, path);
// `_value` is always string in nginx-conf 2.0.0, but its type is declared as
// `string | number`, so we convert it to string to be sure...
return item == null ? item
: Array.isArray(item) ? item.map(({ _value }) => _value == null ? _value : String(_value))
: item._value == null ? undefined
: String(item._value);
},
applyPatch(patch) {
for (const op of patch) {
applyOperation(conf.nginx, op);
}
return this;
},
toString() {
return conf.toString();
},
});
function applyOperation(confRoot, operation) {
const splitPath = operation.path.split('/');
const itemName = splitPath.pop();
const parentPath = splitPath.join('/');
let parent = get(confRoot, parentPath);
if (!parent) {
if (operation.op !== 'remove') {
throw RangeError(`Directive at ${parentPath} does not exist`);
}
return;
}
if (Array.isArray(parent)) {
parent = parent[0];
}
switch (operation.op) {
case 'add':
parent._add(itemName, operation.value);
break;
case 'default':
if (get(confRoot, operation.path) == null) {
parent._add(itemName, operation.value);
}
break;
case 'remove':
// NOTE: ConfItem._remove() does not remove multi-values.
delete parent[itemName];
break;
case 'set':
if (parent[itemName]) {
delete parent[itemName];
}
parent._add(itemName, operation.value);
}
}
function get(confRoot, path) {
const pointer = path === null || path === void 0 ? void 0 : path.split('/');
if (!pointer || pointer[0] !== '') {
throw Error(`Invalid JSON pointer: ${path}`);
}
const len = pointer.length;
if (len === 1) {
return confRoot;
}
for (let i = 1, item = confRoot; i < len; i++) {
const p = pointer[i];
if (Array.isArray(item) && !/\d+/.test(p)) {
item = item[0];
}
item = item === null || item === void 0 ? void 0 : item[p];
if (i === len - 1) {
return item;
}
if (typeof item !== 'object') {
return undefined;
}
}
return undefined;
}
//# sourceMappingURL=nginxConf.js.map