location/api/index.ts

49 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-11-17 00:31:48 +01:00
import type { VercelRequest, VercelResponse } from '@vercel/node'
import fetch from 'cross-fetch'
2021-12-03 01:40:34 +01:00
interface NomadListLocation {
city: string
country: string
country_code: string
latitude: number
longitude: number
epoch_start: number
epoch_end: number
date_start: string
date_end: string
place_photo: string
}
interface NomadListLocationResponse {
location: {
now: NomadListLocation
previous: NomadListLocation
next: NomadListLocation
}
}
2021-12-02 20:13:08 +01:00
export default async (req: VercelRequest, res: VercelResponse) => {
try {
2022-11-17 00:19:53 +01:00
if (!process.env.NOMADLIST_PROFILE) {
throw new Error('Missing NOMADLIST_PROFILE env variable')
}
if (!process.env.NOMADLIST_KEY) {
throw new Error('Missing NOMADLIST_KEY env variable')
}
const response = await fetch(
2021-12-02 20:13:08 +01:00
`https://nomadlist.com/@${process.env.NOMADLIST_PROFILE}.json?key=${process.env.NOMADLIST_KEY}`
)
2022-11-17 00:19:53 +01:00
if (!response || !response.ok || response.status !== 200) {
throw new Error("Couldn't fetch data from NomadList")
}
const json = (await response.json()) as NomadListLocationResponse
2021-12-02 20:13:08 +01:00
2022-11-17 00:19:53 +01:00
res.setHeader('Cache-Control', 's-maxage=1, stale-while-revalidate')
2021-12-02 20:13:08 +01:00
// return only the location part of the data
2022-11-17 00:19:53 +01:00
res.status(200).json(json.location)
2021-12-02 20:13:08 +01:00
} catch (error) {
res.status(500).send(error)
}
}