UNPKG

1.35 kBJavaScriptView Raw
1// @flow
2
3import fetch from 'node-fetch'
4
5import log from './log'
6
7import type { Config, BotContext } from './types'
8
9export const createContext = (config: Config): BotContext => {
10 const callMainframe = (endpoint: string, data: ?Object = {}) => {
11 const url = config.mainframe_url + endpoint
12 log('call %s', url)
13 return fetch(url, {
14 body: JSON.stringify(data),
15 method: 'post',
16 headers: {
17 Authorization: `Mainframe-Bot ${config.mainframe_secret}`,
18 'Content-Type': 'application/json',
19 },
20 }).then(res => {
21 if (res.ok) return res.json()
22 else {
23 const error: Object = new Error(res.statusText)
24 error.status = res.status
25 error.enpoint = endpoint
26 error.data = data
27 throw error
28 }
29 })
30 }
31
32 const sendMessage = (payload: {
33 conversation_id: string,
34 message?: string,
35 data?: Object,
36 }) => callMainframe('/send_message', payload)
37
38 const setupSubscription = (payload: {
39 subscription_token: string,
40 label: string,
41 }) => callMainframe('/setup_subscription', payload)
42
43 const editSubscription = (payload: {
44 subscription_token: string,
45 label?: string,
46 }) => callMainframe('/edit_subscription', payload)
47
48 return {
49 config,
50 callMainframe,
51 sendMessage,
52 setupSubscription,
53 editSubscription,
54 }
55}