UNPKG

1.75 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.createContext = undefined;
7
8var _nodeFetch = require('node-fetch');
9
10var _nodeFetch2 = _interopRequireDefault(_nodeFetch);
11
12var _log = require('./log');
13
14var _log2 = _interopRequireDefault(_log);
15
16function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
18const createContext = exports.createContext = config => {
19 const callMainframe = (endpoint, data = {}) => {
20 const url = config.mainframe_url + endpoint;
21 (0, _log2.default)('call %s', url);
22 return (0, _nodeFetch2.default)(url, {
23 body: JSON.stringify(data),
24 method: 'post',
25 headers: {
26 Authorization: `Mainframe-Bot ${config.mainframe_secret}`,
27 'Content-Type': 'application/json'
28 }
29 }).then(res => {
30 if (res.ok) {
31 return res.status === 204 ? null : res.json();
32 }
33
34 const error = new Error(res.statusText);
35 error.status = res.status;
36 error.enpoint = endpoint;
37 error.data = data;
38
39 if (res.headers.get('Content-Type').indexOf('application/json') !== -1) {
40 return res.json().then(json => {
41 error.response = json;
42 throw error;
43 });
44 } else {
45 return res.text().then(text => {
46 error.response = text;
47 throw error;
48 });
49 }
50 });
51 };
52
53 const sendMessage = payload => callMainframe('/send_message', payload);
54
55 const setupSubscription = payload => callMainframe('/setup_subscription', payload);
56
57 const editSubscription = payload => callMainframe('/edit_subscription', payload);
58
59 return {
60 config,
61 callMainframe,
62 sendMessage,
63 setupSubscription,
64 editSubscription
65 };
66};
\No newline at end of file