UNPKG

integreat-transporter-http

Version:

HTTP transporter for Integreat

51 lines 1.92 kB
import http from 'http'; import pThrottle from 'p-throttle'; import { ensureArray } from './utils/array.js'; import { isNonEmptyString, isObject } from './utils/is.js'; const lowercase = (path) => typeof path === 'string' ? path.toLowerCase() : undefined; const prepareChallenge = ({ scheme, realm, params = {} }) => ({ scheme, realm, params, }); const prepareIncoming = (incoming) => ({ host: ensureArray(incoming.host).map(lowercase).filter(isNonEmptyString), path: ensureArray(incoming.path).map(lowercase).filter(isNonEmptyString), port: incoming.port || 8080, sourceService: incoming.sourceService, challenges: (incoming.challenges || []).map(prepareChallenge), caseSensitivePath: incoming.caseSensitivePath ?? false, }); const servers = {}; const isInvalidThrottleOptions = (options) => isObject(options.throttle) && (typeof options.throttle.limit !== 'number' || typeof options.throttle.interval !== 'number'); function prepareWaitFn(options) { if (options.throttle) { return pThrottle(options.throttle)(async () => undefined); } else { return undefined; } } export default async function connect(options, _authentication, existingConnection) { if (existingConnection && existingConnection.status === 'ok') { return existingConnection; } if (isInvalidThrottleOptions(options)) { return { status: 'badrequest', error: 'Invalid throttle options' }; } const waitFn = prepareWaitFn(options); const connection = { status: 'ok', ...(waitFn ? { waitFn } : {}), }; if (options.incoming) { const incoming = prepareIncoming(options.incoming); const server = servers[incoming.port] || http.createServer(); servers[incoming.port] = server; return { ...connection, server, incoming }; } return connection; } //# sourceMappingURL=connect.js.map