@datastax/astra-db-ts
Version:
Data API TypeScript client
128 lines (127 loc) • 3.45 kB
JavaScript
// Copyright Datastax, Inc
// SPDX-License-Identifier: Apache-2.0
import { BigNumber } from 'bignumber.js';
import { array, define, either, instanceOf } from 'decoders';
export function isNullish(t) {
return t === null || t === undefined;
}
export function jsonTryStringify(value, otherwise) {
try {
return JSON.stringify(value);
}
catch (_) {
return otherwise;
}
}
export function jsonTryParse(json, otherwise, reviver) {
try {
return JSON.parse(json, reviver);
}
catch (_) {
return otherwise;
}
}
export function buildAstraEndpoint(id, region, env = 'prod') {
return 'https://' + id + '-' + region + `.apps${env === 'prod' ? '' : `-${env}`}.astra.datastax.com`;
}
export function toArray(t) {
return Array.isArray(t) ? t : [t];
}
const getJSEnv = () => (typeof globalThis.window !== 'undefined')
? 'browser' :
(typeof globalThis.Buffer !== 'undefined')
? 'server'
: 'unknown';
const env = getJSEnv();
export const forJSEnv = (typeof process !== 'undefined' && typeof process.env === 'object' && process.env.CLIENT_DYNAMIC_JS_ENV_CHECK)
? (fns) => (...args) => fns[getJSEnv()](...args)
: (fns) => fns[env];
export function isBigNumber(value) {
return BigNumber.isBigNumber(value) && 's' in value && 'e' in value && 'c' in value;
}
export const EqualityProof = () => { };
export const oneOrMany = (decoder) => {
return either(decoder, array(decoder));
};
export const function_ = define((fn, ok, err) => {
if (typeof fn === 'function') {
return ok(fn);
}
else {
return err('Input must be a function');
}
});
export const anyInstanceOf = (cls) => instanceOf(cls);
export const numDigits = (n) => {
return (n !== 0) ? Math.floor(Math.log10(Math.abs(n))) + 1 : 1;
};
export function findLast(predicate, orElse) {
return (arr) => {
for (let i = arr.length - 1; i >= 0; i--) {
if (predicate(arr[i], i)) {
return arr[i];
}
}
return orElse;
};
}
export class QueryState {
constructor() {
Object.defineProperty(this, "_state", {
enumerable: true,
configurable: true,
writable: true,
value: QueryState.Unattempted
});
Object.defineProperty(this, "_value", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
}
get state() {
return this._state;
}
swap(value) {
if (isNullish(value)) {
this._state = QueryState.NotFound;
this._value = null;
}
else {
this._state = QueryState.Found;
this._value = value;
}
return this;
}
unwrap() {
return this._value;
}
}
Object.defineProperty(QueryState, "Unattempted", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(QueryState, "Found", {
enumerable: true,
configurable: true,
writable: true,
value: 1
});
Object.defineProperty(QueryState, "NotFound", {
enumerable: true,
configurable: true,
writable: true,
value: 2
});
export function isNonEmpty(arr) {
return arr.length > 0;
}
export function splitWithIncludesCheck(str, sep) {
if (!str.includes(sep)) {
return [str];
}
return str.split(sep);
}