groq-builder
Version:
A **schema-aware**, strongly-typed GROQ query builder. It enables you to build GROQ queries using **auto-completion**, **type-checking**, and **runtime validation**.
56 lines • 2.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const groq_builder_1 = require("../groq-builder");
const utils_1 = require("../types/utils");
groq_builder_1.GroqBuilder.implement({
select(selections, defaultSelection) {
var _a, _b;
const conditions = Object.keys(selections);
const queries = conditions.map((condition) => {
const builder = selections[condition];
return `${condition} => ${builder.query}`;
});
if (defaultSelection) {
queries.push(defaultSelection.query);
}
const parsers = conditions
.map((c) => selections[c].parser)
.filter(utils_1.notNull);
const conditionalParser = parsers.length === 0
? null
: createConditionalParser(parsers, defaultSelection === null || defaultSelection === void 0 ? void 0 : defaultSelection.parser);
// Check that we've got "all or nothing" parsers:
if (parsers.length !== 0 && parsers.length !== conditions.length) {
const missing = conditions.filter((c) => !selections[c].parser);
const err = new TypeError("When using 'select', either all conditions must have validation, or none of them. " +
`Missing validation: "${missing.join('", "')}"`);
// This only works on V8 engines:
(_b = (_a = Error).captureStackTrace) === null || _b === void 0 ? void 0 : _b.call(_a, err, groq_builder_1.GroqBuilder.prototype.select);
throw err;
}
const { newLine, space } = this.indentation;
return this.chain(`select(${newLine}${space}${queries.join(`,${newLine}${space}`)}${newLine})`, conditionalParser);
},
});
function createConditionalParser(parsers, defaultParser) {
return function conditionalParser(input) {
if (input === null && !defaultParser) {
return null;
}
for (const parser of parsers) {
try {
// Returns the first parser that passes without an error:
const result = parser(input);
return result;
}
catch (err) {
// Ignore the error, keep trying
}
}
if (defaultParser) {
return defaultParser(input);
}
throw new TypeError(`Conditional parsing failed; all ${parsers.length} conditions failed`);
};
}
//# sourceMappingURL=select.js.map