import {z} from 'zod' export type Element = {id: number, payload?: {[key: string]: unknown} | undefined, score: number, tie_breaker?: number | undefined}; export type ListPayloadQL = {all_in_sets?: Array | undefined, lists?: Array | undefined, match_metadata?: {[key: string]: unknown} | undefined, payload?: Array | undefined}; export type CreateApiXlistElementsArgs = {errors_only?: boolean | undefined, results?: boolean | undefined, body: ListPayloadQL}; export type CreateApiXlistElementsOptions = {baseUrl: string, jwt?: string | undefined, fetch?: typeof fetch | undefined}; export const rankdbResultlist = z.object({errors: z.record(z.string(), z.unknown()).optional(), success: z.record(z.string(), z.unknown()).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create elements in multiple lists * * POST /xlist/elements */ export const createApiXlistElements = async (args: CreateApiXlistElementsArgs, options: CreateApiXlistElementsOptions) => { const {baseUrl, fetch: fetchFn = fetch, jwt} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/vnd.rankdb.resultlist+json") if (args.errors_only != null) query.append("errors_only", String(args.errors_only)) if (args.results != null) query.append("results", String(args.results)) if (jwt !== undefined) headers.set("Authorization", jwt) const url = `${baseUrl.replace(/\/+$/, '')}/xlist/elements${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(rankdbResultlist, await res.json()) };