import {z} from 'zod' export type GetApiApiV2TemplatesSearchArgs = {page?: number | undefined, limit?: number | undefined, ids?: string | undefined, name?: string | undefined, content?: string | undefined}; export type GetApiApiV2TemplatesSearchOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const messageTemplate = z.object({id: z.number().int(), name: z.string(), content: z.string(), lastModified: z.string().nullable()}); export const searchTemplatesPaginatedResponse = z.object({page: z.number().int(), pageCount: z.number().int(), limit: z.number().int(), resources: z.array(messageTemplate)}); 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 }; /** * Find templates by criteria * * GET /api/v2/templates/search */ export const getApiApiV2TemplatesSearch = async (args: GetApiApiV2TemplatesSearchArgs, options?: GetApiApiV2TemplatesSearchOptions) => { const {baseUrl = "https://rest.textmagic.com", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.ids != null) query.append("ids", String(args.ids)) if (args.name != null) query.append("name", String(args.name)) if (args.content != null) query.append("content", String(args.content)) if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/templates/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(searchTemplatesPaginatedResponse, await res.json()) };