-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (91 loc) · 2.56 KB
/
index.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const helmet = require('helmet')
const convert = require('xml-js')
const XMLHttpRequest = require('xhr2')
const swaggerUI = require('swagger-ui-express')
const { ApolloServer } = require('apollo-server-express')
const schema = require('./modules')
const { responseApi, responseError, transformData } = require('./utils')
const { PROVINCE } = require('./constant')
const docs = require('./docs')
const SWAGGER_CSS_URL =
'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui.min.css'
require('dotenv').config()
const PORT = process.env.PORT || 8080
const app = express()
app.use(helmet()) // security api
app.use(bodyParser.json()) // body parser
app.use(cors()) // handing cors
app.get('/', async (req, res) => {
try {
res.status(200).json({
message: 'Please contact developer for more information',
documentation: `${process.env.HOST}/api-docs`,
})
} catch (error) {
healthcheck.message = error
res.status(503).send()
}
})
app.get('/health', async (req, res) => {
const healthcheck = {
uptime: process.uptime(),
responsetime: process.hrtime(),
message: 'Ok',
timestamp: Date.now(),
}
try {
res.status(200).json(healthcheck)
} catch (error) {
healthcheck.message = error
res.status(503).json()
}
})
app.get('/provinces', async (req, res) => {
try {
responseApi({ res, data: PROVINCE })
} catch (error) {
responseError({ res })
}
})
app.get('/weather/:province_id', async (req, res) => {
try {
let xhr = new XMLHttpRequest()
xhr.open(
'GET',
`${process.env.URL_BMKG_CUACA}/DigitalForecast-${req.params.province_id}.xml`,
)
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = convert.xml2json(xhr.responseText, {
compact: true,
spaces: 4,
})
responseApi({ res, data: transformData(JSON.parse(data)), xhr })
}
if (xhr.readyState === 4 && xhr.status === 404) {
responseApi({ res, xhr })
}
}
xhr.send()
} catch (error) {
responseError({ res })
}
})
async function startServer() {
const server = new ApolloServer({ schema, introspection: true })
await server.start()
server.applyMiddleware({ app })
}
startServer()
app.use(
'/api-docs',
swaggerUI.serve,
swaggerUI.setup(docs, { customCssUrl: SWAGGER_CSS_URL }),
)
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
console.log('Press Ctrl+C to quit.')
})