import {z} from 'zod' export type UserFollowingFeedType = 'ALL' | 'RANKED' | 'CREATOR_ONLY' | 'RANKED_CREATOR_ONLY'; export type GetApiUserAccountFollowingArgs = {ad_account_id?: string | undefined, explicit_following?: boolean | undefined, feed_type?: UserFollowingFeedType | undefined, bookmark?: string | undefined, page_size?: number | undefined}; export type GetApiUserAccountFollowingOptions = {baseUrl?: string | undefined, pinterestOauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const followUser = z.object({type: z.string().optional(), username: z.string().optional()}); export const getApiUserAccountFollowingResponse = z.object({bookmark: z.string().nullable().optional(), items: z.array(followUser)}); 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 }; /** * List following * * GET /user_account/following * * Also accepts auth: client_credentials */ export const getApiUserAccountFollowing = async (args: GetApiUserAccountFollowingArgs, options?: GetApiUserAccountFollowingOptions) => { const {baseUrl = "https://api.pinterest.com/v5", fetch: fetchFn = fetch, pinterestOauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.ad_account_id != null) query.append("ad_account_id", String(args.ad_account_id)) if (args.explicit_following != null) query.append("explicit_following", String(args.explicit_following)) if (args.feed_type != null) query.append("feed_type", String(args.feed_type)) if (args.bookmark != null) query.append("bookmark", String(args.bookmark)) if (args.page_size != null) query.append("page_size", String(args.page_size)) if (pinterestOauth2 !== undefined) headers.set('authorization', `Bearer ${pinterestOauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/user_account/following${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(getApiUserAccountFollowingResponse, await res.json()) };