-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
100 lines (79 loc) · 2.29 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
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const database = require('./database')
database.connect()
const port = process.env.PORT || 8000
const build = 1
const errorHandler = (response, error) => {
console.error('[!] Error', error)
response.status(500).json({
isOk: false,
error: {
code: 500,
message: error.message || '',
stack: process.env.NODE_ENV === 'production' ? {} : (error.stack || {})
},
data: {}
})
}
app.set('trust proxy', 1)
app.use('/api/', bodyParser.json())
let countRequests = 0
app.use('/api/', (request, response, next) => {
console.log(`[.] New API Request (${++countRequests}): ${Date.now().toString()}`)
next()
})
app.get('/', (request, response) => response.send('Hello World!'))
app.get(`/api/v${build}/`, (request, response) => response.json({isOk: true}))
app.get(`/api/v${build}/version/`, (request, response) => {
console.log('[+] Check version')
response.json({
isOk: true,
apiVersion: '0.0.1',
apiBuild: 1
})
})
app.get(`/api/v${build}/:action/`, (request, response) => {
const {query} = request
const {action} = request.params
console.log(`[+] API ${action}:`, query)
database[action](query).then(result => {
response.json({
isOk: true,
data: result
})
}).catch(error => errorHandler(response, error))
})
app.post(`/api/v${build}/:action/`, (request, response) => {
const query = request.body
const {action} = request.params
console.log(`[+] API ${action}:`, query)
database[action](query).then(result => {
response.json({
isOk: true,
data: result
})
}).catch(error => errorHandler(response, error))
})
app.use('/api/', (request, response, next) => {
const error = new Error(`Not found: ${request.originalUrl}`)
next(error)
})
app.use('/api/', (error, request, response, next) => {
let statusCode = request.statusCode === 200 ? 500 : (request.statusCode || 500)
console.error('[!] Error API', error.stack)
if (error.message.includes('Not found')) {
statusCode = 404
}
response.status(statusCode).json({
isOk: false,
error: {
code: statusCode,
message: error.message || '',
stack: process.env.NODE_ENV === 'production' ? {} : (error.stack || {})
},
data: {}
})
})
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))