import {z} from 'zod' export type CreateApiAccountDataSourcesDataSourceSchemaUpdatesArgs = {account: string, data_source: string}; export type CreateApiAccountDataSourcesDataSourceSchemaUpdatesOptions = {baseUrl?: string | undefined, accessTokenAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const link = z.object({href: z.string(), templated: z.boolean().optional()}); export const dataSourceSchemaUpdateLinks = z.object({self: link}); export const dataSourceSchemaUpdateEmbeds = z.unknown(); export const dataSourceSchemaUpdate = z.object({id: z.string(), token: z.string(), state: z.string(), content_length: z.string(), number_of_schemas: z.string(), number_of_tables: z.string(), last_succesful_refresh_at: z.string().optional(), webapp_uri: z.string().optional(), _links: dataSourceSchemaUpdateLinks, _embedded: dataSourceSchemaUpdateEmbeds.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 }; /** * Update data source schema * * POST /{account}/data_sources/{data_source}/schema_updates */ export const createApiAccountDataSourcesDataSourceSchemaUpdates = async (args: CreateApiAccountDataSourcesDataSourceSchemaUpdatesArgs, options?: CreateApiAccountDataSourcesDataSourceSchemaUpdatesOptions) => { const {baseUrl = "https://modeanalytics.com/api", fetch: fetchFn = fetch, accessTokenAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/hal+json") if (accessTokenAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${accessTokenAuth.username}:${accessTokenAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/${encodeURIComponent(String(args.account))}/data_sources/${encodeURIComponent(String(args.data_source))}/schema_updates${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(dataSourceSchemaUpdate, await res.json()) };