-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathgoogle-maps-geocode-proxy.ts
More file actions
54 lines (46 loc) · 1.83 KB
/
Copy pathgoogle-maps-geocode-proxy.ts
File metadata and controls
54 lines (46 loc) · 1.83 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
import { createError, defineEventHandler, getQuery, setHeader } from 'h3'
import { useRuntimeConfig } from 'nitropack/runtime'
import { withQuery } from 'ufo'
import { createCachedJsonFetch, isSafeHttpsUrl } from './utils/cached-upstream'
import { stripProxyAuthQuery } from './utils/proxy-query'
import { withSigning } from './utils/withSigning'
// Addresses rarely change; a 30-day cache avoids billable geocode lookups for
// the same address on every page render. Keyed on the upstream URL (the API
// key is server-injected, so identical across requests).
const cachedGeocodeFetch = createCachedJsonFetch<any>(
'nuxt-scripts-geocode',
2592000,
url => url,
{
allowUrl: url => isSafeHttpsUrl(url) && url.hostname === 'maps.googleapis.com',
contentTypePrefixes: ['application/json'],
},
)
export default withSigning(defineEventHandler(async (event) => {
const runtimeConfig = useRuntimeConfig()
const privateConfig = (runtimeConfig['nuxt-scripts'] as any)?.googleMapsGeocodeProxy
const apiKey = privateConfig?.apiKey
if (!apiKey) {
throw createError({
statusCode: 500,
statusMessage: 'Google Maps API key not configured for geocode proxy',
})
}
const query = stripProxyAuthQuery(getQuery(event))
const { key: _clientKey, ...safeQuery } = query
const geocodeUrl = withQuery('https://maps.googleapis.com/maps/api/geocode/json', {
...safeQuery,
key: apiKey,
})
const data = await cachedGeocodeFetch(geocodeUrl, {
headers: { 'User-Agent': 'Nuxt Scripts Google Geocode Proxy' },
}).catch((error: any) => {
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.statusMessage || 'Failed to geocode',
})
})
setHeader(event, 'Content-Type', 'application/json')
setHeader(event, 'Cache-Control', 'public, max-age=86400, s-maxage=86400')
return data
}))