ok-tools
Version:
My personal JS tools and utilities
83 lines • 3.3 kB
JavaScript
;
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUrlCreator = void 0;
function createUrlCreator(params) {
if (!params.urlBase || !params.urlBase.length) {
throw new Error('params.urlBase is required!');
}
var idKeyName = params.idKeyName;
var idKeyNameDefinite;
var slugKeyName = params.slugKeyName;
if (!idKeyName && idKeyName !== false) {
idKeyNameDefinite = 'id';
}
else {
idKeyNameDefinite = idKeyName;
}
if (!slugKeyName && slugKeyName !== false) {
slugKeyName = 'url';
}
var startUrlWith = params.urlBase;
if (typeof params.addFirstSlash === 'undefined' || params.addFirstSlash) {
if (startUrlWith.length < 1 || startUrlWith[0][0] !== '/') {
startUrlWith[0] = '/' + startUrlWith[0];
}
}
// @ts-ignore
return function (idOrObjectWithId, slug) {
if (slug === void 0) { slug = ''; }
if (typeof idOrObjectWithId === 'object'
&& ((idKeyNameDefinite !== false && idOrObjectWithId[idKeyNameDefinite]) || idKeyNameDefinite === false)) {
var theSlugValueAsStringOrArray = slugKeyName ? (idOrObjectWithId[slugKeyName] || '') : '';
var theSlugValue = void 0;
if (Array.isArray(theSlugValueAsStringOrArray)) {
if (params.firstSlugOnlyIfArray) {
theSlugValue = theSlugValueAsStringOrArray[0];
}
else {
theSlugValue = theSlugValueAsStringOrArray.join('-');
}
}
else {
theSlugValue = theSlugValueAsStringOrArray;
}
var theIdValue = idKeyNameDefinite ? (idOrObjectWithId[idKeyNameDefinite] || '') : '';
if (params.idKeyNameIfSlugIsMissing && !theSlugValue) {
theIdValue = idOrObjectWithId[params.idKeyNameIfSlugIsMissing] || '';
}
if (theSlugValue || slug) {
var slugValue = theSlugValue || slug;
if (theIdValue) {
return __spreadArray(__spreadArray([], startUrlWith), [theIdValue, slugValue]);
}
else {
return __spreadArray(__spreadArray([], startUrlWith), [slugValue]);
}
}
else {
if (theIdValue) {
return __spreadArray(__spreadArray([], startUrlWith), [theIdValue]);
}
else {
return __spreadArray([], startUrlWith);
}
}
}
if (typeof idOrObjectWithId === 'string') {
if (slug) {
return __spreadArray(__spreadArray([], startUrlWith), [idOrObjectWithId, slug]);
}
else {
return __spreadArray(__spreadArray([], startUrlWith), [idOrObjectWithId]);
}
}
throw new Error('Invalid parameters to create URL.');
};
}
exports.createUrlCreator = createUrlCreator;
//# sourceMappingURL=url-creator.js.map