import {z} from 'zod' export type GetApiAnalyticsArgs = {period?: ('7d' | '30d' | '90d' | 'all') | undefined, platform?: string | undefined, limit?: number | undefined}; export type GetApiAnalyticsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const analyticsResult = z.object({period: z.string().optional(), summary: z.object({totals: z.record(z.string(), z.number()).optional(), byPlatform: z.record(z.string(), z.record(z.string(), z.number())).optional()}).optional(), posts: z.array(z.object({postId: z.string().optional(), caption: z.string().nullable().optional(), publishedAt: z.string().nullable().optional(), platform: z.string().optional(), views: z.number().nullable().optional(), likes: z.number().nullable().optional(), comments: z.number().nullable().optional(), shares: z.number().nullable().optional(), reach: z.number().nullable().optional(), saves: z.number().nullable().optional(), impressions: z.number().nullable().optional(), reposts: z.number().nullable().optional(), totalInteractions: z.number().nullable().optional(), fetchedAt: z.string().nullable().optional(), error: z.string().nullable().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 }; /** * Read post analytics (refreshed hourly) * * GET /analytics */ export const getApiAnalytics = async (args: GetApiAnalyticsArgs, options?: GetApiAnalyticsOptions) => { const {baseUrl = "https://api.posteahora.com/functions/v1/api", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.period != null) query.append("period", String(args.period)) if (args.platform != null) query.append("platform", String(args.platform)) if (args.limit != null) query.append("limit", String(args.limit)) if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/analytics${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(analyticsResult, await res.json()) };