import {z} from 'zod' export type GetApiSocialMediaChannelMetricsArgs = {channel_id: string, date_from: string, date_to?: string | undefined, output?: ('json' | 'csv' | 'xml' | 'php') | undefined}; export type GetApiSocialMediaChannelMetricsOptions = {baseUrl?: string | undefined, http?: string | undefined, fetch?: typeof fetch | undefined}; export const socialMediaChannelMetrics = z.object({metrics: z.array(z.object({follower_count: z.number().int().optional(), retrieved_at: z.string().optional()})).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 }; /** * Channel metrics * * GET /social-media/channel-metrics */ export const getApiSocialMediaChannelMetrics = async (args: GetApiSocialMediaChannelMetricsArgs, options?: GetApiSocialMediaChannelMetricsOptions) => { const {baseUrl = "https://api.ahrefs.com/v3", fetch: fetchFn = fetch, http} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.channel_id != null) query.append("channel_id", String(args.channel_id)) if (args.date_from != null) query.append("date_from", String(args.date_from)) if (args.date_to != null) query.append("date_to", String(args.date_to)) if (args.output != null) query.append("output", String(args.output)) if (http !== undefined) headers.set('authorization', `Bearer ${http}`) const url = `${baseUrl.replace(/\/+$/, '')}/social-media/channel-metrics${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(socialMediaChannelMetrics, await res.json()) };