-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
77 lines (66 loc) · 1.64 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
const Koa = require('koa')
const next = require('next')
const koaBody = require('koa-body')
const router = require('koa-router')()
const Database = require('./db')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const server = new Koa()
const db = new Database()
app.prepare().then(() => {
server.use(
koaBody({
jsonLimit: '500kb'
})
)
server.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
server.use(async (ctx, next) => {
ctx.res.statusCode = 200
await next()
})
router.post('/api/create', async ctx => {
const { data, expiry, friendly } = ctx.request.body
const id = await db.create(data, expiry, friendly)
ctx.body = {
ok: true,
id: id
}
})
router.get('/api/read/:id', async ctx => {
const data = await db.read(ctx.params.id)
ctx.body = {
ok: !!data,
data: data
}
})
router.get('/about', async ctx => {
await handle(ctx.req, ctx.res)
ctx.respond = false
})
router.get('/:id', async ctx => {
const enc = await db.read(ctx.params.id)
if (!enc) ctx.redirect('/')
await app.render(
ctx.req,
ctx.res,
'/decrypt',
Object.assign(ctx.params, ctx.query, { enc: enc })
)
ctx.respond = false
})
router.get('*', async ctx => {
await handle(ctx.req, ctx.res)
ctx.respond = false
})
server.use(router.routes())
server.listen(3000, err => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})