UNPKG

889 BJavaScriptView Raw
1// @flow
2
3import fetch from 'node-fetch'
4
5import type { Config, BotContext, Handlers } from './types'
6
7export const createContext = (
8 config: Config,
9 handlers: Handlers,
10): BotContext => {
11 const callMainframe = (endpoint: string, data: ?Object = {}) => {
12 return fetch(config.mainframe_url + endpoint, {
13 body: JSON.stringify(data),
14 method: 'post',
15 headers: {
16 Authorization: `Mainframe-Bot ${config.mainframe_secret}`,
17 'Content-Type': 'application/json',
18 },
19 }).then(res => {
20 if (res.ok) return res.json()
21 else {
22 const error: Object = new Error(res.statusText)
23 error.status = res.status
24 error.enpoint = endpoint
25 error.data = data
26 throw error
27 }
28 })
29 }
30
31 const sendEvent = (payload: ?Object) => callMainframe('/event', payload)
32
33 return { config, callMainframe, sendEvent }
34}