/**
* https://www.metaweather.com/api/#location
*
* USAGE:
* https://badgen.net/runkit/vladimyr/metaweather/44418/state
* https://badgen.net/runkit/vladimyr/metaweather/44418/temperature
* https://badgen.net/runkit/vladimyr/metaweather/44418/temperature/f
* https://badgen.net/runkit/vladimyr/metaweather/44418/wind
* https://badgen.net/runkit/vladimyr/metaweather/44418/wind/mph
* https://badgen.net/runkit/vladimyr/metaweather/44418/humidity
*/
const axios = require('axios')
const { send } = require('micro')
const client = axios.create({ baseURL: 'https://www.metaweather.com/api/' })
exports.endpoint = async function (req, res) {
const args = req.url.split('/').filter(Boolean)
if (args.length < 2) {
return send(res, 400, {
subject: 'metaweather',
status: 'malformed args',
color: 'grey'
})
}
try {
send(res, 200, await getWeather(...args))
} catch (err) {
send(res, err.response ? err.response.status : 400, {
subject: 'metaweather',
status: 'invalid',
color: 'grey'
})
}
}
async function getWeather(woeid, topic, ...args) {
const { title, consolidated_weather: info } = await client.get(`/location/${woeid}`).then(res => res.data)
switch (topic) {
case 'state':
return {
subject: `${title} (state)`,
status: info[0].weather_state_name,
color: 'green'
}
case 'temp':
case 'temperature': {
const subject = `${title} (temp)`
const color = 'green'
const temp = info[0].the_temp
const unit = args[0]
if (unit === 'f') {
const value = Math.round(temp * 9/5) + 32
const status = `${value}°F`
return { subject, status, color }
}
const value = Math.round(temp)
const status = `${value}°C`
return { subject, status, color }
}
case 'wind': {
const subject = `${title} (wind)`
const color = 'green'
const directions = {
N: '↓',
NNE: '↓',
NE: '↙',
ENE: '←',
E: '←',
ESE: '←',
SE: '↖',
SSE: '↑',
S: '↑',
SSW: '↑',
SW: '↗',
WSW: '→',
W: '→',
WNW: '→',
NW: '↘',
NNW: '↓'
}
const direction = directions[info[0].wind_direction_compass]
const speed = info[0].wind_speed
const unit = args[0]
if (unit === 'mph') {
const value = Math.round(speed)
const status = `${direction}${value}mph`
return { subject, status, color }
}
const value = Math.round(speed * 1.609)
const status = `${direction}${value}km/h`
return { subject, status, color }
}
case 'humidity':
return {
subject: `${title} (humidity)`,
status: info[0].humidity,
color: 'green'
}
}
return {
subject: 'metaweather',
status: 'unknown',
color: 'grey'
}
}