import type { HttpClient } from '@services' import { http } from '../http/client' import { type HttpClientType, omyHttp } from '../httpExternal/omyClient' import type { MapboxApiError, MapboxGeocodingResponse, MapboxSearchOptions, } from './types' export class GeoCoding { private http = {} as HttpClient constructor( private provider: { apiUrl: string apiKey: string httpClientType: HttpClientType }, ) { this.http = this.setHttp(this.provider.httpClientType) } private setHttp(httpClientType: HttpClientType) { const api = { name: 'mapbox', url: this.provider.apiUrl } as const return httpClientType === 'axios' ? http({ api, unserialized: true }) : omyHttp({ api }) } /** Get place(s) based on a string query */ async forwardSearch(q: string, options: Partial = {}) { const safeOptions = Object.fromEntries( Object.entries(options) .filter(([_, val]) => typeof val !== 'undefined') .map(([key, val]) => [key, val.toString()]), ) const query = new URLSearchParams({ access_token: this.provider.apiKey, autocomplete: 'true', limit: '4', q, types: 'country,region,places', ...safeOptions, }).toString() const response = await this.http.get< MapboxGeocodingResponse & { errors?: MapboxApiError } >(`search/geocode/v6/forward?${query}`) if (response.errors) { throw response.errors } return response.features ?? [] } }