import {z} from 'zod' export type Element = {id: number, payload?: {[key: string]: unknown} | undefined, score: number, tie_breaker?: number | undefined}; export type PutMultiElementsPayload = Array; export type UpdateApiListsListIdElementsArgs = {list_id: string, results?: boolean | undefined, body: PutMultiElementsPayload}; export type UpdateApiListsListIdElementsOptions = {baseUrl: string, jwt?: string | undefined, fetch?: typeof fetch | undefined}; export const rankdbElement = z.object({from_bottom: z.number().int(), from_top: z.number().int(), id: z.number().int().gte(0), list_id: z.string().min(2).max(100), payload: z.record(z.string(), z.unknown()), score: z.number().int().gte(0), tie_breaker: z.number().int().gte(0).lte(4294967295), updated_at: z.string()}); export const rankdbElementCollection = z.array(rankdbElement); export const rankdbMultielement = z.object({found: rankdbElementCollection, not_found: z.array(z.number().int()).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 }; /** * Update Multiple Elements * * PUT /lists/{list_id}/elements */ export const updateApiListsListIdElements = async (args: UpdateApiListsListIdElementsArgs, options: UpdateApiListsListIdElementsOptions) => { 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.multielement+json") if (args.results != null) query.append("results", String(args.results)) if (jwt !== undefined) headers.set("Authorization", jwt) const url = `${baseUrl.replace(/\/+$/, '')}/lists/${encodeURIComponent(String(args.list_id))}/elements${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", 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(rankdbMultielement, await res.json()) };