import {z} from 'zod' export type GetApiSearchArgs = {limit?: number | undefined, name: string, active_only?: boolean | undefined, terminated?: boolean | undefined}; export type GetApiSearchOptions = {baseUrl?: string | undefined, Auth0?: string | undefined, fetch?: typeof fetch | undefined}; export const searchResult = z.object({id: z.number().int().optional(), entity_type: z.string().optional(), name: z.string().optional()}); export const listMetadata = z.object({status: z.string(), count: z.number().int(), total_count: z.number().int().optional(), offset: z.number().int().optional(), next_page: z.string().optional(), prev_page: z.string().optional()}); export const getApiSearchResponse = z.object({data: z.object({organizations: z.array(searchResult).optional(), agencies: z.array(searchResult).optional(), advertisers: z.array(searchResult).optional()}).optional(), meta: listMetadata.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 }; /** * Search Entities * * GET /search */ export const getApiSearch = async (args: GetApiSearchArgs, options?: GetApiSearchOptions) => { const {baseUrl = "https://api.mediamath.com/api/v3.0", fetch: fetchFn = fetch, Auth0} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.name != null) query.append("name", String(args.name)) if (args.active_only != null) query.append("active_only", String(args.active_only)) if (args.terminated != null) query.append("terminated", String(args.terminated)) if (Auth0 !== undefined) headers.set('authorization', `Bearer ${Auth0}`) const url = `${baseUrl.replace(/\/+$/, '')}/search${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(getApiSearchResponse, await res.json()) };