import {z} from 'zod' export type Latitude = number; export type Longitude = number; export type CustomDeviceId = string; export type GetApiLocationGeoArgs = {lat: Latitude, lon: Longitude, 'x-custom-device-id'?: CustomDeviceId | undefined}; export type GetApiLocationGeoOptions = {baseUrl?: string | undefined, OrganizationAuthToken?: string | undefined, fetch?: typeof fetch | undefined}; export const latitude = z.number(); export const longitude = z.number(); export const uncertainty = z.number(); export const geoAddressFormatted = z.string(); export const geoCountry = z.string(); export const geoState = z.string(); export const geoCountryCode = z.string(); export const geoCounty = z.string(); export const geoPostalCode = z.string(); export const geoStateCode = z.string(); export const geoCity = z.string(); export const geoSuburb = z.string(); export const geoStreet = z.string(); export const geoStreetNumber = z.string(); export const reverseGeoAddress = z.object({country: geoCountry, state: geoState, countryCode: geoCountryCode.optional(), county: geoCounty.optional(), postalCode: geoPostalCode.optional(), stateCode: geoStateCode.optional(), city: geoCity.optional(), suburb: geoSuburb.optional(), street: geoStreet.optional(), streetNumber: geoStreetNumber.optional()}); export const reverseGeoResponse = z.object({lat: latitude, lon: longitude, uncertainty: uncertainty, formatted: geoAddressFormatted, address: reverseGeoAddress}); 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 }; /** * GetAddressDataFromCoordinates * * GET /location/geo * * Also accepts auth: JSON Web Token */ export const getApiLocationGeo = async (args: GetApiLocationGeoArgs, options?: GetApiLocationGeoOptions) => { const {baseUrl = "https://api.nrfcloud.com/v1", fetch: fetchFn = fetch, OrganizationAuthToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.lat != null) query.append("lat", String(args.lat)) if (args.lon != null) query.append("lon", String(args.lon)) if (args['x-custom-device-id'] != null) headers.set("x-custom-device-id", String(args['x-custom-device-id'])) if (OrganizationAuthToken !== undefined) headers.set('authorization', `Bearer ${OrganizationAuthToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/location/geo${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(reverseGeoResponse, await res.json()) };