@datastax/astra-db-ts
Version:
Data API TypeScript client
114 lines (113 loc) • 3.51 kB
JavaScript
// Copyright Datastax, Inc
// SPDX-License-Identifier: Apache-2.0
import { findLast, isNullish, splitWithIncludesCheck } from '../lib/utils.js';
export class OptionParseError extends Error {
constructor(message, field) {
super(message);
Object.defineProperty(this, "field", {
enumerable: true,
configurable: true,
writable: true,
value: field
});
}
}
export class OptionsHandler {
constructor(decoder) {
Object.defineProperty(this, "decoder", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "parseable", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "parsed", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.decoder = decoder;
}
parse(input, field) {
try {
return asParsed(this.decoder.verify(input));
}
catch (e) {
if (!(e instanceof Error && e.name === 'Decoding error')) {
throw e;
}
const message = (!isNullish(field))
? `Error parsing '${field}': ${e.message}`
: e.message;
throw new OptionParseError(message, field);
}
}
parseWithin(obj, field) {
return this.parse(obj?.[splitWithIncludesCheck(field, '.').at(-1)], field);
}
}
export class MonoidalOptionsHandler extends OptionsHandler {
constructor(decoder, monoid) {
super(decoder);
Object.defineProperty(this, "monoid", {
enumerable: true,
configurable: true,
writable: true,
value: monoid
});
Object.defineProperty(this, "empty", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.empty = asParsed(monoid.empty);
}
concat(configs) {
if (configs.length <= 1) {
return configs[0] ?? this.empty; // minor optimization
}
return asParsed(this.monoid.concat(configs));
}
concatParse(configs, raw, field) {
return this.concat([...configs, this.parse(raw, field)]);
}
concatParseWithin(configs, obj, field) {
return this.concat([...configs, this.parseWithin(obj, field)]);
}
}
const asParsed = (input) => input;
export const monoids = {
optional: () => ({
empty: undefined,
concat: findLast((a) => a !== undefined && a !== null),
}),
array: () => ({
empty: [],
concat: (as) => as.flat(),
}),
prependingArray: () => ({
empty: [],
concat: (as) => as.reduce((acc, next) => [...next, ...acc], []),
}),
object(schema) {
const schemaEntries = Object.entries(schema);
const empty = Object.fromEntries(schemaEntries.map(([k, v]) => [k, v.empty]));
const concat = (configs) => {
const result = { ...empty };
for (const config of configs) {
for (const [key, monoid] of schemaEntries) {
result[key] = monoid.concat([result[key], config[key]]);
}
}
return result;
};
return { empty, concat };
},
};