Skip to content

Commit

Permalink
refactor(back-end): update request-promise to node-fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
weronikaolejniczak committed May 14, 2024
1 parent d2fcb96 commit 384d453
Show file tree
Hide file tree
Showing 8 changed files with 251 additions and 201 deletions.
2 changes: 1 addition & 1 deletion apps/back-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
"dotenv": "^16.4.5",
"express": "^4.19.2",
"http-status": "^1.7.4",
"node-fetch": "^3.3.2",
"request": "^2.88.2",
"request-promise": "^4.2.6",
"url": "^0.11.3"
},
"devDependencies": {
Expand Down
10 changes: 5 additions & 5 deletions apps/back-end/src/models/Hotel.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
interface HotelParams {
amenities: string[];
breakfast?: boolean;
breakfast?: string[];
checkInExtra?: string;
checkInHours?: string;
checkOutHours?: string;
creditCardPaymentPossible?: boolean;
description: string;
dupeId?: string;
frontDesk24H?: boolean;
image: string;
location: string;
name: string;
image?: string;
location: { address: string; latitude: number; longitude: number };
name?: string;
offer?: string;
phone: string;
phone?: string;
rating?: number;
}

Expand Down
6 changes: 3 additions & 3 deletions apps/back-end/src/models/Weather.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ interface WeatherParams {
humidity: number;
windSpeed: number;
cloudiness: number;
description: string;
description?: string;
rain?: number;
icon: string;
main: string;
icon?: string;
main?: string;
}

function createWeather({
Expand Down
42 changes: 32 additions & 10 deletions apps/back-end/src/services/fetchCoordinates.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,35 @@
import request from 'request-promise';

const fetchCoordinates = (keyword: string) => {
return request({
method: 'GET',
uri: encodeURI(
`https://api.tomtom.com/search/2/geocode/${keyword}.json?key=${process.env.TOM_TOM_API_KEY}`,
),
json: true,
}).then((data) => data.results[0].position);
interface TomTomSearchResponse {
results: {
position: {
lat: number;
lon: number;
};
}[];
}

const fetchCoordinates = async (
keyword: string,
): Promise<{ lat: number; lon: number } | null> => {
const url = encodeURI(
`https://api.tomtom.com/search/2/geocode/${keyword}.json?key=${process.env.TOM_TOM_API_KEY}`,
);

try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);

const data: TomTomSearchResponse = await response.json();

if (data.results.length > 0 && data.results[0]?.position) {
return data.results[0].position;
} else {
console.warn('No results found');
return null;
}
} catch (error) {
console.error('Fetch failed: ', error);
throw error;
}
};

export default fetchCoordinates;
72 changes: 51 additions & 21 deletions apps/back-end/src/services/fetchUnsplashImage.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,62 @@
import request from 'request-promise';
import fetch from 'node-fetch';

const defaultImage = {
interface UnsplashUser {
name: string;
username: string;
}

interface UnsplashUrl {
regular: string;
}

interface UnsplashResult {
urls: UnsplashUrl;
user: UnsplashUser;
}

interface UnsplashResponse {
results: UnsplashResult[];
}

interface UnsplashImage {
authorName: string;
imageUrl: string;
username: string;
}

const defaultImage: UnsplashImage = {
authorName: 'Annie Spratt',
imageUrl:
'https://images.unsplash.com/photo-1488646953014-85cb44e25828?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1866&q=80',
username: 'anniespratt',
};

const fetchUnsplashImage = (keyword: string) => {
return request({
method: 'GET',
uri: encodeURI(
`https://api.unsplash.com/search/photos?page=1&query=${keyword}&client_id=${process.env.UNSPLASH_API_KEY}`,
),
json: true,
})
.then((data) => {
const imageUrl = data.results[0].urls.regular.toString();
const authorName = data.results[0].user.name.toString();
const username = data.results[0].user.username.toString();

const image = { authorName, imageUrl, username };

return image;
})
.catch(() => {
const fetchUnsplashImage = async (keyword: string): Promise<UnsplashImage> => {
const uri = encodeURI(
`https://api.unsplash.com/search/photos?page=1&query=${keyword}&client_id=${process.env.UNSPLASH_API_KEY}`,
);

try {
const response = await fetch(uri);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = (await response.json()) as UnsplashResponse;

if (data.results.length > 0 && data.results[0]) {
const imageUrl = data.results[0].urls.regular;
const authorName = data.results[0].user.name;
const username = data.results[0].user.username;

return { authorName, imageUrl, username };
} else {
console.warn('No results found for the keyword');
return defaultImage;
});
}
} catch (error) {
console.error('Fetch failed: ', error);
return defaultImage;
}
};

export default fetchUnsplashImage;
126 changes: 81 additions & 45 deletions apps/back-end/src/services/fetchWeather.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,86 @@
import request from 'request-promise';

import fetch from 'node-fetch';
import createWeather from '../models/Weather';

const fetchWeather = (latitude: string, longitude: string) => {
return request({
method: 'GET',
uri: encodeURI(
`http:api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude={hourly,current,minutely}&APPID=${process.env.WEATHER_API_KEY}&units=metric`,
),
json: true,
})
.then((data) => {
console.log(data);
const timezone = {
timezone: data.timezone,
offset: data.timezone_offset,
};
const forecast: ReturnType<typeof createWeather>[] = [];

data.daily.map((day) =>
forecast.push(
createWeather({
date: new Date(day.dt * 1000),
sunrise: new Date(day.sunrise * 1000),
sunset: new Date(day.sunset * 1000),
maxTemp: day.temp.max,
minTemp: day.temp.min,
tempDay: day.temp.day,
tempNight: day.temp.night,
tempDayFeelsLike: day.feels_like.day,
tempNightFeelsLike: day.feels_like.night,
pressure: day.pressure,
humidity: day.humidity,
windSpeed: day.wind_speed,
cloudiness: day.clouds,
description: day.weather[0].description,
rain: day.pop,
icon: day.weather[0].icon,
main: day.weather[0].main,
}),
),
);

return [forecast, timezone];
})
.catch((error) => error);
interface WeatherDay {
dt: number;
sunrise: number;
sunset: number;
temp: {
max: number;
min: number;
day: number;
night: number;
};
feels_like: {
day: number;
night: number;
};
pressure: number;
humidity: number;
wind_speed: number;
clouds: number;
weather: {
description: string;
icon: string;
main: string;
}[];
pop: number;
}

interface WeatherAPIResponse {
timezone: string;
timezone_offset: number;
daily: WeatherDay[];
}

const fetchWeather = async (
latitude: string,
longitude: string,
): Promise<
[ReturnType<typeof createWeather>[], { timezone: string; offset: number }]
> => {
const uri = encodeURI(
`http://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=hourly,current,minutely&APPID=${process.env.WEATHER_API_KEY}&units=metric`,
);

try {
const response = await fetch(uri);
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);

const data = (await response.json()) as WeatherAPIResponse;

const timezone = {
timezone: data.timezone,
offset: data.timezone_offset,
};

const forecast: ReturnType<typeof createWeather>[] = data.daily.map((day) =>
createWeather({
date: new Date(day.dt * 1000),
sunrise: new Date(day.sunrise * 1000),
sunset: new Date(day.sunset * 1000),
maxTemp: day.temp.max,
minTemp: day.temp.min,
tempDay: day.temp.day,
tempNight: day.temp.night,
tempDayFeelsLike: day.feels_like.day,
tempNightFeelsLike: day.feels_like.night,
pressure: day.pressure,
humidity: day.humidity,
windSpeed: day.wind_speed,
cloudiness: day.clouds,
description: day.weather[0]?.description,
rain: day.pop,
icon: day.weather[0]?.icon,
main: day.weather[0]?.main,
}),
);

return [forecast, timezone];
} catch (error) {
console.error('Fetch failed: ', error);
throw error;
}
};

export default fetchWeather;
Loading

0 comments on commit 384d453

Please sign in to comment.