import {z} from 'zod' export type KeywordUpdateItem = {archived?: boolean | undefined, bid?: (number | null) | undefined, id: string}; export type KeywordsUpdate = {keywords?: Array | undefined}; export type PatchApiAdAccountsAdAccountIdKeywordsArgs = {ad_account_id: string, body: KeywordsUpdate}; export type PatchApiAdAccountsAdAccountIdKeywordsOptions = {baseUrl?: string | undefined, pinterestOauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const matchType = z.enum(["BROAD", "PHRASE", "EXACT", "EXACT_NEGATIVE", "PHRASE_NEGATIVE"]); export const keyword = z.object({archived: z.boolean().optional(), bid: z.number().int().nullable().optional(), id: z.string(), match_type: matchType.nullable(), parent_id: z.string(), parent_type: z.string().optional(), type: z.string().optional(), value: z.string()}); export const keywordError = z.object({data: keyword.optional(), error_messages: z.array(z.string()).optional()}); export const keywords = z.object({errors: z.array(keywordError), keywords: z.array(keyword)}); 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 keywords * * PATCH /ad_accounts/{ad_account_id}/keywords */ export const patchApiAdAccountsAdAccountIdKeywords = async (args: PatchApiAdAccountsAdAccountIdKeywordsArgs, options?: PatchApiAdAccountsAdAccountIdKeywordsOptions) => { const {baseUrl = "https://api.pinterest.com/v5", fetch: fetchFn = fetch, pinterestOauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (pinterestOauth2 !== undefined) headers.set('authorization', `Bearer ${pinterestOauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/ad_accounts/${encodeURIComponent(String(args.ad_account_id))}/keywords${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PATCH", 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(keywords, await res.json()) };