UNPKG

2.8 kBJavaScriptView Raw
1// @flow
2
3import bodyParser from 'koa-bodyparser'
4import Router from 'koa-router'
5
6import log from './log'
7
8import type { BotContext, Handlers } from './types'
9
10export const createRouter = (
11 handlers: Handlers,
12 context: BotContext,
13): Router => {
14 log('create router with handlers: %s', Object.keys(handlers).join(', '))
15
16 const router = new Router()
17 router.use(bodyParser({ enableTypes: ['json'] }))
18
19 router.post('/enable', ctx => {
20 handlers.enable && handlers.enable(ctx.request.body || {}, context)
21 ctx.body = { success: true }
22 })
23
24 router.post('/disable', ctx => {
25 handlers.disable && handlers.disable(ctx.request.body || {}, context)
26 ctx.body = { success: true }
27 })
28
29 router.post('/conversation_added', ctx => {
30 handlers.conversation_added &&
31 handlers.conversation_added(ctx.request.body || {}, context)
32 ctx.body = { success: true }
33 })
34
35 router.post('/conversation_removed', ctx => {
36 handlers.conversation_removed &&
37 handlers.conversation_removed(ctx.request.body || {}, context)
38 ctx.body = { success: true }
39 })
40
41 router.post('/edit_subscription', ctx => {
42 handlers.edit_subscription &&
43 handlers.edit_subscription(ctx.request.body || {}, context)
44 ctx.body = { success: true }
45 })
46
47 router.post('/delete_subscription', ctx => {
48 handlers.delete_subscription &&
49 handlers.delete_subscription(ctx.request.body || {}, context)
50 ctx.body = { success: true }
51 })
52
53 router.post('/mention', ctx => {
54 handlers.mention && handlers.mention(ctx.request.body || {}, context)
55 ctx.body = { success: true }
56 })
57
58 router.post('/post', async ctx => {
59 if (!handlers.post) {
60 ctx.body = { success: false, message: 'post endpoint not implemented' }
61 return
62 }
63
64 const params = ctx.request.body || {}
65
66 let missingParam
67 if (!params.data) {
68 missingParam = 'data'
69 } else if (!params.context) {
70 missingParam = 'context'
71 }
72
73 if (missingParam) {
74 ctx.status = 400
75 ctx.body = `Missing ${missingParam}`
76 return
77 }
78
79 try {
80 const res = handlers.post(params, context)
81 const payload = res && res.then ? await res : res
82 ctx.body = payload || { success: true }
83 } catch (err) {
84 log('error handling post request', params, err)
85 ctx.status = 500
86 }
87 })
88
89 router.post('/preview', async ctx => {
90 if (!handlers.preview) {
91 ctx.body = { success: false }
92 return
93 }
94
95 const params = ctx.request.body || {}
96
97 try {
98 const res = handlers.preview(params, context)
99 const payload = res && res.then ? await res : res
100 ctx.body = payload || { success: true }
101 } catch (err) {
102 log('error handling preview request', params, err)
103 ctx.status = 500
104 }
105 })
106
107 return router
108}