-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (58 loc) · 1.62 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
const request = require('request')
const Koa = require('koa')
const body = require('koa-body')
const koajwt = require('koa-jwt')
const cors = require('@koa/cors')
const router = require('./server/router')
const port = process.env.PORT || 8080
const app = new Koa()
app.use(cors({
origin: '*',
credentials: true,
}))
app.use(body({ multipart: true }))
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.statusCode || err.status || 500
ctx.body = {
status: ctx.status,
message: err.message,
data: []
}
ctx.app.emit('error', err, ctx)
}
})
app.use(koajwt({
secret: process.env.JWT_SECRET,
cookie: 'token',
passthrough: true,
}))
const MAX = 1024
const tldr = json => {
if (json !== undefined && json !== null) {
const string = JSON.stringify(json)
return string.length > MAX ? `${string.substring(0, MAX)}...` : string
}
return json
}
app.use(async ({ request, response, state: { user: { username = 'anonymous' } = {} } }, next) => {
console.info(username, request.ip, request.protocol, request.method, request.url, '>>', tldr(request.body))
await next()
console.info(username, request.ip, request.protocol, request.method, request.url, '<<', response.status, tldr(response.body))
})
app.use(router.routes(), router.allowedMethods())
// app.use(async (ctx) => {
// if (ctx.url === '/') {
// ctx.body = 'welcome home'
// return
// }
// if (ctx.method === 'GET' && ctx.status === 404) {
// console.info(ctx.url, 'redirecting to /home')
// ctx.body = request(`http://localhost:${port}/`)
// }
// })
app.listen(port, () => {
console.log(`server is listening at port ${port}`)
})