@datastax/astra-db-ts
Version:
Data API TypeScript client
58 lines (57 loc) • 2.02 kB
JavaScript
// Copyright Datastax, Inc
// SPDX-License-Identifier: Apache-2.0
import { boolean, constant, define, either, inexact, nullish, object, optional, positiveInteger, taggedUnion, } from 'decoders';
import { function_ } from '../../lib/utils.js';
import { OptionsHandler } from '../../lib/opts-handlers.js';
import { FetchH2, FetchNative } from '../../lib/index.js';
import { betterTypeOf } from '../../documents/utils.js';
const fetchH2 = define((module, ok, err) => {
if (module && typeof module === 'object') {
const verified = inexact({
TimeoutError: function_,
context: function_,
}).verify({
TimeoutError: module.TimeoutError,
context: module.context,
});
return ok(verified);
}
else {
return err(`fetchH2 should be set to \`import * as fetchH2 from 'fetch-h2'\` or \`const fetchH2 = require('fetch-h2')\`; got ${betterTypeOf(module)}`);
}
});
const decoder = nullish(taggedUnion('client', {
'fetch-h2': object({
client: constant('fetch-h2'),
preferHttp2: optional(boolean),
http1: optional(object({
keepAlive: optional(boolean),
keepAliveMS: optional(positiveInteger),
maxSockets: optional(positiveInteger),
maxFreeSockets: optional(either(positiveInteger, constant(Infinity))),
})),
fetchH2: fetchH2,
}),
'fetch': object({
client: constant('fetch'),
}),
'custom': object({
client: constant('custom'),
fetcher: inexact({
fetch: function_,
close: optional(function_),
}),
}),
}));
const transformer = decoder.transform((opts) => {
const ctx = (opts?.client === 'fetch-h2')
? new FetchH2(opts) :
(opts?.client === 'custom')
? opts.fetcher
: new FetchNative();
return {
ctx: ctx,
closed: { ref: false },
};
});
export const HttpOptsHandler = new OptionsHandler(transformer);