You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
docuri/index.js

83 lines
1.4 KiB
JavaScript

10 years ago
/*
10 years ago
* docuri: Rich document ids for CouchDB.
10 years ago
*
* Copyright (c) 2014 null2 GmbH Berlin
* Licensed under the MIT license.
*/
10 years ago
// type/id/subtype/index/version
var DEFINITION = ['type', 'id', 'subtype', 'index', 'version'];
10 years ago
function docuri(definition) {
if (definition) {
DEFINITION = definition;
10 years ago
return docuri;
}
return DEFINITION;
}
docuri.parts = function(obj) {
if (typeof obj === 'string') {
obj = docuri.parse(obj);
}
var parts = DEFINITION.map(function(part) {
return obj[part];
});
while (parts.length && typeof parts[parts.length - 1] === 'undefined') {
parts.pop();
}
return parts;
};
docuri.parse = function(str) {
10 years ago
str = str || '';
10 years ago
10 years ago
return str.split('/').reduce(function(obj, value, i) {
if (value) {
obj[DEFINITION[i]] = value;
10 years ago
}
10 years ago
10 years ago
return obj;
}, {});
10 years ago
};
docuri.stringify = function(obj) {
10 years ago
obj = obj || {};
return docuri.parts(obj).join('/');
10 years ago
};
docuri.merge = function(obj, objToMerge) {
10 years ago
objToMerge = objToMerge || {};
if (typeof obj === 'string') {
obj = docuri.parse(obj);
}
10 years ago
DEFINITION.forEach(function(part) {
10 years ago
if (objToMerge[part]) {
obj[part] = objToMerge[part];
}
10 years ago
});
return docuri.stringify(obj);
};
docuri.arity = function(obj) {
if (typeof obj === 'string') {
obj = docuri.parse(obj);
}
return docuri.parts(obj).length;
};
module.exports = docuri;