import {z} from 'zod' export type BatchOperation = {method: 'add' | 'edit' | 'delete', object_id?: string | undefined, object?: {[key: string]: unknown} | undefined, trigger_webhook?: boolean | undefined}; export type BatchRequest = {operations: Array}; export type CreateApiBucketsSlugObjectsBatchArgs = {body: BatchRequest}; export type CreateApiBucketsSlugObjectsBatchOptions = {baseUrl?: string | undefined, writeKey?: string | undefined, fetch?: typeof fetch | undefined}; export const metadata = z.record(z.string(), z.unknown()); export const object = z.object({id: z.string().optional(), type: z.string().optional(), title: z.string().optional(), slug: z.string().optional(), status: z.enum(["published", "draft"]).optional(), content: z.string().nullable().optional(), metadata: metadata.optional(), bucket: z.string().optional(), thumbnail: z.string().nullable().optional(), locale: z.string().nullable().optional(), created_at: z.string().optional(), created_by: z.string().optional(), modified_at: z.string().optional(), modified_by: z.string().optional(), published_at: z.string().nullable().optional(), publish_at: z.union([z.string(), z.number()]).nullable().optional(), unpublish_at: z.union([z.string(), z.number()]).nullable().optional(), assigned_to: z.string().nullable().optional(), assigned_by: z.string().nullable().optional(), assigned_at: z.string().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const batchResponse = z.object({operations: z.array(z.object({method: z.enum(["add", "edit", "delete"]).optional(), status: z.enum(["success", "error"]).optional(), object: object.optional(), message: z.string().optional()}).and(z.record(z.string(), z.unknown())))}); 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 }; /** * Batch create, update, and delete Objects * * POST /buckets/{slug}/objects/batch */ export const createApiBucketsSlugObjectsBatch = async (args: CreateApiBucketsSlugObjectsBatchArgs, options?: CreateApiBucketsSlugObjectsBatchOptions) => { const {baseUrl = "https://api.cosmicjs.com/v3", fetch: fetchFn = fetch, writeKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (writeKey !== undefined) headers.set('authorization', `Bearer ${writeKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/buckets/${encodeURIComponent(String(args.slug))}/objects/batch${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(batchResponse, await res.json()) };