32 lines
946 B
TypeScript
32 lines
946 B
TypeScript
import axios from 'axios';
|
|
import { Address } from './types';
|
|
const dotenv = require('dotenv');
|
|
|
|
dotenv.config();
|
|
|
|
const GEOCODING_API_KEY = process.env.GEOCODING_API_KEY;
|
|
|
|
|
|
// will return at least - street, line1, line2, country, postcode
|
|
export const resolveAddress = async (searchTerm: string): Promise<Address> => {
|
|
try {
|
|
const response = await axios.get(`https://api.geoapify.com/v1/geocode/search?text=${searchTerm}&format=json&apiKey=${GEOCODING_API_KEY}`);
|
|
if (response.data.results.length > 0) {
|
|
const result = response.data.results[0];
|
|
console.log(result)
|
|
return {
|
|
country: result.country,
|
|
street: result.street,
|
|
line1: result.address_line1,
|
|
line2: result.address_line2,
|
|
postcode: result.postcode,
|
|
code: result.country_code.toUpperCase()
|
|
}
|
|
} else {
|
|
throw new Error('No results found');
|
|
}
|
|
} catch (error) {
|
|
throw error.message;
|
|
}
|
|
};
|