1 |
|
2 |
|
3 | import bodyParser from 'body-parser'
|
4 | import { Router } from 'express'
|
5 |
|
6 | import log from './log'
|
7 |
|
8 | import type { BotContext, Handlers } from './types'
|
9 |
|
10 | const jsonParser = bodyParser.json()
|
11 |
|
12 | export const createRouter = (
|
13 | handlers: Handlers,
|
14 | context: BotContext,
|
15 | ): Router => {
|
16 | log('create router with handlers: %s', Object.keys(handlers).join(', '))
|
17 |
|
18 | const router = new Router()
|
19 |
|
20 | router.use(jsonParser)
|
21 |
|
22 | if (handlers.enable) {
|
23 | router.post('/enable', (req, res) => {
|
24 | handlers.enable(req.body || {}, context)
|
25 | res.sendStatus(200)
|
26 | })
|
27 | }
|
28 |
|
29 | if (handlers.disable) {
|
30 | router.post('/disable', (req, res) => {
|
31 | handlers.disable(req.body || {}, context)
|
32 | res.sendStatus(200)
|
33 | })
|
34 | }
|
35 |
|
36 | if (handlers.conversation_added) {
|
37 | router.post('/conversation_added', (req, res) => {
|
38 | handlers.conversation_added(req.body || {}, context)
|
39 | res.sendStatus(200)
|
40 | })
|
41 | }
|
42 |
|
43 | if (handlers.conversation_removed) {
|
44 | router.post('/conversation_removed', (req, res) => {
|
45 | handlers.conversation_removed(req.body || {}, context)
|
46 | res.sendStatus(200)
|
47 | })
|
48 | }
|
49 |
|
50 | if (handlers.edit_subscription) {
|
51 | router.post('/edit_subscription', (req, res) => {
|
52 | handlers.edit_subscription(req.body || {}, context)
|
53 | res.sendStatus(200)
|
54 | })
|
55 | }
|
56 |
|
57 | if (handlers.delete_subscription) {
|
58 | router.post('/delete_subscription', (req, res) => {
|
59 | handlers.delete_subscription(req.body || {}, context)
|
60 | res.sendStatus(200)
|
61 | })
|
62 | }
|
63 |
|
64 | if (handlers.post) {
|
65 | router.post('/post', async (req, res) => {
|
66 | const params = req.body || {}
|
67 | if (!params.user_id) {
|
68 | return res.status(400).send('Missing user_id')
|
69 | }
|
70 | if (!params.data) {
|
71 | return res.status(400).send('Missing data')
|
72 | }
|
73 | if (!params.context) {
|
74 | return res.status(400).send('Missing context')
|
75 | }
|
76 | try {
|
77 | const postResult = handlers.post(params, context)
|
78 | const payload = postResult.then ? await postResult : postResult
|
79 | if (payload) {
|
80 | res.send(payload)
|
81 | } else {
|
82 | res.send({ success: true })
|
83 | }
|
84 | } catch (err) {
|
85 | log('error handling post request', params, err)
|
86 | res.sendStatus(500)
|
87 | }
|
88 | })
|
89 | }
|
90 |
|
91 | return router
|
92 | }
|