import {z} from 'zod' export type SocialPostTypeEnum = 'EVENT' | 'OFFER' | 'ANNOUNCEMENT' | 'COVID19' | 'PRODUCT'; export type SitesType = 'GOOGLE' | 'FACEBOOK'; export type PostMessageInput = {site: SitesType, message: string}; export type PostCtaInput = {site: SitesType, type: string, url: string}; export type MediaTypeEnum = 'IMAGE' | 'VIDEO'; export type SocialPostMediaInput = {site: SitesType, url: string, type?: MediaTypeEnum | undefined}; export type PostScheduledDatesInput = {startDatetime: string, endDatetime: string, removalSites?: Array | undefined}; export type PostContextInfoInput = {couponCode?: string | undefined, redeemUrl?: string | undefined, termsConditions?: string | undefined, title?: string | undefined, discount?: string | undefined, locationType?: string | undefined, startDay?: string | undefined, startTime?: string | undefined, endDay?: string | undefined, endTime?: string | undefined}; export type ProductInfoInput = {productId?: string | undefined, name?: string | undefined, category?: string | undefined, price?: string | undefined, minPrice?: string | undefined, maxPrice?: string | undefined, description?: string | undefined, photo?: string | undefined, cta?: Array | undefined, sites?: Array | undefined}; export type CreateSocialPostMutationInput = {postName: string, locationIds: Array, postType: SocialPostTypeEnum, postSites: Array, postMessage?: Array | undefined, postCta?: Array | undefined, postMediaUrl?: Array | undefined, postScheduledDates?: PostScheduledDatesInput | undefined, postContextInfo?: PostContextInfoInput | undefined, componentIdentifier?: string | undefined, componentType?: string | undefined, products?: Array | undefined, clientMutationId?: string | undefined}; export type CreateApiApiV4PostsArgs = {body: {input: CreateSocialPostMutationInput}}; export type CreateApiApiV4PostsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const contextError = z.object({key: z.string().optional(), value: z.string().optional()}); export const mutationError = z.object({message: z.string().optional(), code: z.string().optional(), contextInfo: z.array(contextError).optional()}); export const socialPostStatusEnum = z.enum(["INPROGRESS", "SCHEDULED", "SUCCESS", "ERROR", "DELETED", "EXPIRED"]); export const socialPostTypeEnum = z.enum(["EVENT", "OFFER", "ANNOUNCEMENT", "COVID19", "PRODUCT"]); export const sitesType = z.enum(["GOOGLE", "FACEBOOK"]); export const postMessage = z.object({message: z.string().optional(), site: sitesType.optional()}); export const siteCtaTypes = z.object({value: z.string().optional(), label: z.string().optional()}); export const postCta = z.object({type: siteCtaTypes.optional(), url: z.string().optional(), site: sitesType.optional(), tinyUrl: z.string().optional()}); export const postContextInfo = z.object({couponCode: z.string().optional(), redeemUrl: z.string().optional(), termsConditions: z.string().optional(), title: z.string().optional(), discount: z.string().optional(), locationType: z.string().optional(), startDay: z.string().optional(), startTime: z.string().optional(), endDay: z.string().optional(), endTime: z.string().optional()}); export const mediaTypeEnum = z.enum(["IMAGE", "VIDEO"]); export const socialPostMedia = z.object({url: z.string().optional(), site: sitesType.optional(), type: mediaTypeEnum.optional()}); export const publishStatusEnum = z.enum(["PUBLISHING", "PUBLISHED", "DELETED", "EXPIRED", "ERROR"]); export const socialPostPublishDetail = z.object({site: sitesType.optional(), status: publishStatusEnum.optional(), createdDate: z.string().optional(), publishedDate: z.string().optional(), deletedDate: z.string().optional(), expiredDate: z.string().optional(), submissionError: z.string().optional()}); export const socialPostPublishedLink = z.object({site: sitesType.optional(), link: z.string().optional()}); export const socialPost = z.object({id: z.string(), name: z.string(), status: socialPostStatusEnum, type: socialPostTypeEnum, createdAt: z.string(), deletedAt: z.string().optional(), expiredAt: z.string().optional(), scheduledStartDate: z.string().optional(), scheduledEndDate: z.string().optional(), views: z.number().int().optional(), clicks: z.number().int().optional(), shares: z.number().int().optional(), reactions: z.number().int().optional(), comments: z.number().int().optional(), sites: z.array(sitesType), message: z.array(postMessage).optional(), cta: z.array(postCta).optional(), contextInfo: postContextInfo.optional(), mediaUrl: z.array(socialPostMedia).optional(), publishDetails: z.array(socialPostPublishDetail).optional(), postLinks: z.array(socialPostPublishedLink).optional(), locationIds: z.array(z.number().int())}); export const socialPostMutation = z.object({clientMutationId: z.string().optional(), success: z.boolean(), errors: z.array(mutationError).optional(), socialPost: socialPost.optional()}); export const apiError = z.object({message: z.string(), code: z.string().optional(), contextInfo: z.array(z.object({key: z.string().optional(), value: z.string().optional()})).optional()}); export const createApiApiV4PostsResponse = z.object({data: z.object({createSocialPost: socialPostMutation.optional()}), errors: z.array(apiError).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 }; /** * Create social posts for multiple locations. * * POST /api/v4/posts * * Also accepts auth: rapidApiKey + rapidApiHost */ export const createApiApiV4Posts = async (args: CreateApiApiV4PostsArgs, options?: CreateApiApiV4PostsOptions) => { const {baseUrl = "https://listingsapi.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("Authorization", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/api/v4/posts${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", 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(createApiApiV4PostsResponse, await res.json()) };