rfc6570-expand
Version:
A template processor for RFC 6570 URI Template
55 lines (54 loc) • 2.24 kB
JavaScript
;
const variables_1 = require('./variables');
const expression_parser_1 = require('./expression-parser');
const parser = expression_parser_1.expressionParser();
const varSpecToString = (allow, ifemp, named, sep, varName, explode, maxLength, value, isEmpty) => {
if (typeof maxLength !== 'undefined') {
if (variables_1.isString(value)) {
return (named ? varName + (isEmpty ? ifemp : '=') : '') +
allow(value.substring(0, maxLength));
}
else {
throw new Error();
}
}
return (explode
? (variables_1.isArray(value)
? value.map(v => {
return (named ? varName + (isEmpty ? ifemp : '=') : '') +
allow(v);
}).join(sep)
: (variables_1.isString(value)
? allow(value)
: value.map(([k, v]) => {
return allow(k) + (isEmpty ? ifemp : '=') + allow(v);
}).join(sep)))
: ((named ? varName + (isEmpty ? ifemp : '=') : '') +
(variables_1.isArray(value)
? value.map(allow).join(',')
: (variables_1.isString(value)
? allow(value)
: value.map(([k, v]) => {
return allow(k) + ',' + allow(v);
}).join(',')))));
};
const expression = (s, variables) => {
const { operator: { allow, first, ifemp, named, sep }, varSpecs } = parser(s);
return varSpecs
.map(varSpec => {
const { varName } = varSpec;
const value = variables[varName];
return { value: value, varSpec: varSpec };
})
.filter(({ value }) => {
return variables_1.isDefined(value) &&
!(value.length === 0 && (variables_1.isArray(value) || variables_1.isObject(value)));
})
.map(({ value, varSpec: { varName, maxLength, explode }, }, index) => {
const isFirst = index === 0;
const isEmpty = value.length === 0;
const firstOrSep = (isFirst ? first : sep);
return firstOrSep + varSpecToString(allow, ifemp, named, sep, varName, explode, maxLength, value, isEmpty);
}).join('');
};
exports.expression = expression;