-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
78 lines (76 loc) · 2.55 KB
/
server.js
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
72
73
74
75
76
77
78
const dev = process.env.NODE_ENV !== 'production'
if (dev) {
require('dotenv').config()
}
const routes = require('./routes')
const next = require('next')
const { createServer } = require('http')
const port = parseInt(process.env.PORT, 10) || 3000
const app = next({ dev })
const handle = routes.getRequestHandler(app)
const axios = require('axios')
const { serverRuntimeConfig: { GOOGLE_API_TOKEN } } = require('./next.config')
const { parse } = require('url')
const { join } = require('path')
const fs = require('fs').promises
const server = createServer(async (req, res) => {
const { pathname, query } = parse(req.url, true)
if (pathname.includes('/getNearbyCafes')) {
try {
const { lat, long } = query
// type=cafe
const { data } = await axios(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},${long}&radius=100&key=${GOOGLE_API_TOKEN}`)
res.writeHead(200, {'Content-Type': 'application/json'})
res.write(JSON.stringify(data))
res.end()
} catch (error) {
console.log(error)
res.end(req)
}
}
if (pathname.includes('/getById')) {
try {
const { id } = query
const { data } = await axios(`https://maps.googleapis.com/maps/api/place/details/json?placeid=${id}&fields=photos,place_id,formatted_address,name,rating,opening_hours&key=${GOOGLE_API_TOKEN}`)
res.writeHead(200, {'Content-Type': 'application/json'})
res.write(JSON.stringify(data))
res.end()
} catch (error) {
console.log(error)
res.end(query)
}
}
if (pathname.includes('/search')) {
try {
const { inputText } = query
const { data } = await axios(`https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=${inputText}&inputtype=textquery&fields=place_id,formatted_address,name,opening_hours&key=${GOOGLE_API_TOKEN}`)
res.writeHead(200, {'Content-Type': 'application/json'})
res.write(JSON.stringify(data))
res.end()
} catch (error) {
console.log(error)
res.end(req)
}
}
if (pathname.includes('/service-worker.js')) {
try {
const filePath = join(__dirname, '.next', 'service-worker.js')
const file = await fs.readFile(filePath)
res.writeHead(200, {'Content-Type': 'application/javascript'})
res.write(file)
res.end()
} catch (error) {
console.log(error)
res.end(req)
}
} else {
handle(req, res)
}
})
app.prepare()
.then(() => {
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})