import {z} from 'zod' export type GetApiV1CollectionsArgs = {page_size?: number | undefined, cursor?: string | undefined, order_by?: string | undefined, direction?: string | undefined, blacklist?: string | undefined}; export type GetApiV1CollectionsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const collection = z.object({address: z.string().min(1), name: z.string().min(1), description: z.string().min(1), icon_url: z.string().min(1), collection_image_url: z.string().min(1), project_id: z.number(), metadata_api_url: z.string().min(1)}); export const collectionList = z.object({result: z.array(collection), cursor: z.string().min(1), remaining: z.number()}); 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 }; /** * Get a list of collections * * GET /v1/collections */ export const getApiV1Collections = async (args: GetApiV1CollectionsArgs, options?: GetApiV1CollectionsOptions) => { const {baseUrl = "https://api.x.immutable.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page_size != null) query.append("page_size", String(args.page_size)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.order_by != null) query.append("order_by", String(args.order_by)) if (args.direction != null) query.append("direction", String(args.direction)) if (args.blacklist != null) query.append("blacklist", String(args.blacklist)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/collections${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(collectionList, await res.json()) };