import { DocumentSchema } from "./Documents"; import { arrayableParams } from "./Types"; import type { UnionArrayKeys, ExtractBaseTypes, SearchParams } from "./Types"; function hasNoArrayValues< TDoc extends DocumentSchema, T extends SearchParams, const Infix extends string, >(params: T | ExtractBaseTypes): params is ExtractBaseTypes { return Object.keys(arrayableParams) .filter((key) => params[key] !== undefined) .every((key) => isNonArrayValue(params[key])); } export function normalizeArrayableParams< TDoc extends DocumentSchema, T extends SearchParams, const Infix extends string, >(params: T): Prettify> { const result = { ...params }; const transformedValues = Object.keys(arrayableParams) .filter((key) => Array.isArray(result[key])) .map((key) => { result[key] = result[key].join(","); return key; }); if (!transformedValues.length && hasNoArrayValues(result)) { return result; } if (!hasNoArrayValues(result)) { throw new Error( `Failed to normalize arrayable params: ${JSON.stringify(result)}`, ); } return result; } function isNonArrayValue< TDoc extends DocumentSchema, T extends SearchParams, const Infix extends string, K extends UnionArrayKeys, >(value: T[K] | ExtractBaseTypes[K]): value is ExtractBaseTypes[K] { return !Array.isArray(value); } type Prettify = { [K in keyof T]: T[K]; // eslint-disable-next-line @typescript-eslint/no-empty-object-type } & {}; interface ErrorWithMessage extends Error { message: string; } function isErrorWithMessage(error: unknown): error is ErrorWithMessage { return ( typeof error === "object" && error !== null && "message" in error && typeof (error as Record).message === "string" ); } export function toErrorWithMessage(couldBeError: unknown): ErrorWithMessage { if (isErrorWithMessage(couldBeError)) return couldBeError; try { if (typeof couldBeError === "string") { return new Error(couldBeError); } return new Error(JSON.stringify(couldBeError)); } catch { return new Error(String(couldBeError)); } }