// @flow import bodyParser from 'koa-bodyparser' import Router from 'koa-router' import log from './log' import type { BotContext, Handlers } from './types' export const createRouter = ( handlers: Handlers, context: BotContext, ): Router => { log('create router with handlers: %s', Object.keys(handlers).join(', ')) const router = new Router() router.use(bodyParser({ enableTypes: ['json'] })) router.post('/enable', ctx => { handlers.enable && handlers.enable(ctx.request.body || {}, context) ctx.body = { success: true } }) router.post('/disable', ctx => { handlers.disable && handlers.disable(ctx.request.body || {}, context) ctx.body = { success: true } }) router.post('/conversation_added', ctx => { handlers.conversation_added && handlers.conversation_added(ctx.request.body || {}, context) ctx.body = { success: true } }) router.post('/conversation_removed', ctx => { handlers.conversation_removed && handlers.conversation_removed(ctx.request.body || {}, context) ctx.body = { success: true } }) router.post('/edit_subscription', ctx => { handlers.edit_subscription && handlers.edit_subscription(ctx.request.body || {}, context) ctx.body = { success: true } }) router.post('/delete_subscription', ctx => { handlers.delete_subscription && handlers.delete_subscription(ctx.request.body || {}, context) ctx.body = { success: true } }) router.post('/mention', ctx => { handlers.mention && handlers.mention(ctx.request.body || {}, context) ctx.body = { success: true } }) router.post('/post', async ctx => { if (!handlers.post) { ctx.body = { success: false, message: 'post endpoint not implemented' } return } const params = ctx.request.body || {} let missingParam if (!params.data) { missingParam = 'data' } else if (!params.context) { missingParam = 'context' } if (missingParam) { ctx.status = 400 ctx.body = `Missing ${missingParam}` return } try { const res = handlers.post(params, context) const payload = res && res.then ? await res : res ctx.body = payload || { success: true } } catch (err) { log('error handling post request', params, err) ctx.status = 500 } }) router.post('/preview', async ctx => { if (!handlers.preview) { ctx.body = { success: false } return } const params = ctx.request.body || {} try { const res = handlers.preview(params, context) const payload = res && res.then ? await res : res ctx.body = payload || { success: true } } catch (err) { log('error handling preview request', params, err) ctx.status = 500 } }) return router }