import type { CountryCodes } from '@entities' import type { HttpClient } from '@services' import { http } from '../http/client' import { omyHttp } from '../httpExternal/omyClient' import type { HttpClientType } from '../httpExternal/omyClient' export type ApiLocationResponseType = { data?: { ip: string type: string hostname: string | null currency: { code: string name: string name_native: string } location: { continent: { code: string name: string } country: { area: number calling_code: string capital: string code: CountryCodes name: string population: number population_density: number languages: [ { code: string name: string }, ] tld: string } region: { code: string | null name: string | null } city: string postal: string latitude: number longitude: number language: { code: string name: string native: string } in_eu: boolean } time_zone: { id: string abbreviation: string current_time: Date name: string offset: number } } } export class UserLocation { private apiKey = '' private http = {} as HttpClient private apiUrl = '' constructor( private provider: { apiUrl: string apiKey: string httpClientType: HttpClientType }, ) { this.apiKey = this.provider.apiKey this.apiUrl = this.provider.apiUrl this.http = this.setHttp(this.provider.httpClientType) } private setHttp(httpClientType: HttpClientType) { const api = { name: 'ipLocation', url: this.apiUrl } as const return httpClientType === 'axios' ? http({ api, unserialized: true }) : omyHttp({ api }) } async getUserLocation() { const resLocationInfos = await this.http .get(`?key=${this.apiKey}`) .then((res) => typeof res.data === 'object' ? res : ({ data: res } as unknown as ApiLocationResponseType), ) .catch(console.error) if (resLocationInfos?.data) { return { location: { countryCode: resLocationInfos.data?.location?.country?.code, country: resLocationInfos.data?.location?.country?.name, city: resLocationInfos.data?.location?.city, postal: resLocationInfos.data?.location?.postal, }, currency: resLocationInfos.data?.currency?.code, timezone: resLocationInfos.data?.time_zone?.id, } } } }