// @flow import fetch from 'node-fetch' import log from './log' import type { Config, BotContext } from './types' export const createContext = (config: Config): BotContext => { const callMainframe = (endpoint: string, data: ?Object = {}) => { const url = config.mainframe_url + endpoint log('call %s', url) return fetch(url, { body: JSON.stringify(data), method: 'post', headers: { Authorization: `Mainframe-Bot ${config.mainframe_secret}`, 'Content-Type': 'application/json', }, }).then(res => { if (res.ok) { return res.status === 204 ? null : res.json() } const error: Object = new Error(res.statusText) error.status = res.status error.enpoint = endpoint error.data = data if (res.headers.get('Content-Type').indexOf('application/json') !== -1) { return res.json().then(json => { error.response = json throw error }) } else { return res.text().then(text => { error.response = text throw error }) } }) } const sendMessage = (payload: { conversation_id: string, message?: string, data?: Object, }) => callMainframe('/send_message', payload) const setupSubscription = (payload: { subscription_token: string, label: string, }) => callMainframe('/setup_subscription', payload) const editSubscription = (payload: { subscription_token: string, label?: string, }) => callMainframe('/edit_subscription', payload) return { config, callMainframe, sendMessage, setupSubscription, editSubscription, } }