import {z} from 'zod' export type StoreId = string; export type GetApiManagerLoyaltyV1SourceUserSearchArgs = {'X-Store-Id': StoreId, token?: string | undefined, limit: string, source: string, term: string}; export type GetApiManagerLoyaltyV1SourceUserSearchOptions = {baseUrl?: string | undefined, OAuth20?: string | undefined, fetch?: typeof fetch | undefined}; export const userField = z.object({key: z.string().optional(), value: z.string().optional()}); export const user = z.object({id: z.string().optional(), userFields: z.array(userField).optional()}); export const searchUsersResponse = z.object({users: z.array(user).optional(), offsetToken: z.string().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 }; /** * Search loyalty users * * GET /manager/loyalty/v1/{source}/user/search */ export const getApiManagerLoyaltyV1SourceUserSearch = async (args: GetApiManagerLoyaltyV1SourceUserSearchArgs, options?: GetApiManagerLoyaltyV1SourceUserSearchOptions) => { const {baseUrl = "https://partners.tryotter.com", fetch: fetchFn = fetch, OAuth20} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['X-Store-Id'] != null) headers.set("X-Store-Id", String(args['X-Store-Id'])) if (args.token != null) query.append("token", String(args.token)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.term != null) query.append("term", String(args.term)) if (OAuth20 !== undefined) headers.set('authorization', `Bearer ${OAuth20}`) const url = `${baseUrl.replace(/\/+$/, '')}/manager/loyalty/v1/${encodeURIComponent(String(args.source))}/user/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(searchUsersResponse, await res.json()) };