JSFiddle - React, Tailwind, and code Playground
JavaScript
class OpenWeatherService {
constructor() {
this.appid = '...';
this.apiDomain = 'https://api.openweathermap.org/data/2.5/';
}
async getWeatherForGeo(lon, lat) {
let endpointUrl = new URL(this.apiDomain);
endpointUrl.pathname += 'weather';
endpointUrl.search = new URLSearchParams({
appid: this.appid,
lat: lat,
lon: lon,
units: "imperial"
});
let response = await fetch(endpointUrl.toString());
let json = await response.json();
return json;
}
async getWeatherForCity(city) {
let endpointUrl = new URL(this.apiDomain);
endpointUrl.pathname += 'weather';
endpointUrl.search = new URLSearchParams({
appid: this.appid,
q: city,
units: "imperial"
});
let response = await fetch(endpointUrl.toString());
let json = await response.json();
return json;
}
}
class OpenWeatherAdaptor {
translateOutput(response) {
if( response.message ) {
return {
error: "We are temporarily unable to get weather data, please check back soon!"
}
} else {
return {
locale: response.name,
currentTemp: response.main.temp,
high: response.main.temp_max,
low: response.main.temp_min,
condition: response.weather[0].description
}
}
}
async getWeather(byWhat, args) {
const ws = new OpenWeatherService();
let response;
if( byWhat == 'city' ) {
response = await ws.getWeatherForCity(...args);
} else {
response = await ws.getWeatherForGeo(...args);
}
return this.translateOutput(response);
}
}
(new OpenWeatherAdaptor()).getWeather('city', ['Mountainview']).then(weather => console.log(weather));