import {z} from 'zod' export type DashboardPost = {graphs?: Array | undefined}; export type CreateApiDashboardsArgs = {sellerId?: number | undefined, warehouse?: string | undefined, range?: string | undefined, rangeStart?: string | undefined, rangeEnd?: string | undefined, body: DashboardPost}; export type CreateApiDashboardsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const data = z.object({slug: z.string().optional(), data: z.array(z.string()).optional(), labels: z.array(z.string()).optional()}); export const error = z.object({graph: z.string().optional(), reason: z.string().optional()}); export const response = z.object({data: z.array(data).optional(), errors: z.array(error).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 }; /** * Request dashboards * * POST /dashboards */ export const createApiDashboards = async (args: CreateApiDashboardsArgs, options?: CreateApiDashboardsOptions) => { const {baseUrl = "https://api.quivo.co", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.sellerId != null) query.append("sellerId", String(args.sellerId)) if (args.warehouse != null) query.append("warehouse", String(args.warehouse)) if (args.range != null) query.append("range", String(args.range)) if (args.rangeStart != null) query.append("rangeStart", String(args.rangeStart)) if (args.rangeEnd != null) query.append("rangeEnd", String(args.rangeEnd)) const url = `${baseUrl.replace(/\/+$/, '')}/dashboards${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(response, await res.json()) };