-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweather.service.js
More file actions
71 lines (66 loc) · 2.2 KB
/
Copy pathweather.service.js
File metadata and controls
71 lines (66 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict'
const BASE_URL = 'https://api.openweathermap.org/data/2.5/onecall'
const API_KEY = '81b29166d4b3448f6540eab75f83777c'
const DEFAULT_OPTIONS = {
coord: { lon: -75.76, lat: 45.35 }, // Algonquin College
units: 'metric'
}
const cache = new Map()
/**
* @typedef {Object} APIOptions
* @property {string} units [metric, imperial, standard]
* @property {Object} coord Location coordinates
* @property {number} coord.lon Longitude
* @property {number} coord.lat Latitude
*/
/**
* Get the latest weather forecast for the given location.
* Results are cached for 10 minutes.
* @param {APIOptions} options
* @returns {Object} Forecast results
* @see https://openweathermap.org/api/one-call-api#data
*/
export async function getForecast(options) {
const { coord, units } = Object.assign({}, DEFAULT_OPTIONS, options)
const cacheItem = cache.get(coord)
if (cacheItem && !isExpired(cacheItem.current.dt)) {
return cacheItem
}
const forecast = await fetchForecast({ units, coord })
cache.set(coord, forecast)
return forecast
/**
* Helper function to check cache expiry
* @param {number} cacheTime UNIX timestamp in seconds
*/
function isExpired(cacheTime) {
const TEN_MINUTES = 600 // seconds
const currentTime = Math.floor(Date.now() / 1000) // convert from ms to s
const elapsedTime = currentTime - cacheTime
return elapsedTime > TEN_MINUTES
}
}
/**
* Private function to make the actual `fetch()` call to the API
* @param {APIOptions} options
*/
async function fetchForecast({ coord: { lat, lon }, units }) {
const url = `${BASE_URL}?lat=${lat}&lon=${lon}&units=${units}&appid=${API_KEY}`
const response = await fetch(url)
if (!response.ok) throw new Error(response.statusText)
return response.json()
}
/**
* Returns an <img> HTMLElement with the correct URL to display
* the OpenWeather image corresponding to the given `iconCode`.
* @param {string} iconCode
*/
export function createWeatherIcon(iconCode) {
let img = document.createElement('img')
img.setAttribute(
'src',
'https://openweathermap.org/img/wn/' + iconCode + '@4x.png'
)
img.setAttribute('alt', '')
return img
}