pig-dam-core
Version:
Library that should be included in every Pig DAM project we build
57 lines (56 loc) • 1.75 kB
JavaScript
;
/**
* Date: 2019-07-13
* Time: 13:42
* @license MIT (see project's LICENSE file)
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseUrn = exports.createUrn = void 0;
const shortid = require("shortid");
/**
* Creates a urn either by <param>path</param> or by <param>parts</param>:
* - path: "urn:<path>:<nss>"
* - parts: "urn:<path[0]>:<path[2]>...<path[n-1]>:<nss>"
*/
function createUrn({ path, nss = shortid.generate() }) {
return (Array.isArray(path))
? `urn:${path.join(":")}:${nss}`
: `urn:${path}:${nss}`;
}
exports.createUrn = createUrn;
/**
* Parses a urn and returns bits
* @param urn - the whole urn
* @param parts - optionally may specify the names of the parts in which case the
* result will be an object of values mapped to these part names.
* @throws {Error}
*/
function parseUrn(urn, parts) {
const match = urn.match(/^urn:(([\w_-]+):){1,}([\w_-]+)$/);
if (match === null) {
throw new Error(`invalid urn "${urn}"`);
}
else {
const split = urn.split(":");
if (parts === undefined) {
return {
nss: split[split.length - 1],
parts: split.slice(1, split.length - 1)
};
}
else {
if (parts.length !== split.length - 2) {
throw new Error(`parts=${JSON.stringify(parts)} is mismatched with urn ${urn}`);
}
return {
nss: split[split.length - 1],
parts: parts.reduce((result, part, index) => {
result[part] = split[index + 1];
return result;
}, {})
};
}
}
}
exports.parseUrn = parseUrn;