-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathgoogle-maps-geocode-proxy.ts
More file actions
42 lines (35 loc) · 1.25 KB
/
google-maps-geocode-proxy.ts
File metadata and controls
42 lines (35 loc) · 1.25 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
import { useRuntimeConfig } from '#imports'
import { createError, defineEventHandler, getQuery, setHeader } from 'h3'
import { $fetch } from 'ofetch'
import { withQuery } from 'ufo'
import { withSigning } from './utils/withSigning'
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 = getQuery(event)
const { key: _clientKey, ...safeQuery } = query
const geocodeUrl = withQuery('https://maps.googleapis.com/maps/api/geocode/json', {
...safeQuery,
key: apiKey,
})
const data = await $fetch(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
}))