@@ -1,67 +1,36 @@
1−import * as http from 'http';
2−import Maybe from 'folktale/maybe';
3−
41//NOTE if accessing this in a localhost configuration fails with "CORS request
52// did not succeed", you might need to visit localhost:3001 or whatever
63// explicitly and tell your browser that's safe to access.
74// https://stackoverflow.com/a/53011185/1334324
8−const baseOptions = {
9− hostname: 'localhost',
10− port: 3001,
11− protocol: 'https:',
12− headers: { 'Content-Type': 'application/json' }, //TODO text/plain vs application/json
13− json: true
14−}
5+const baseUrl = 'https://localhost:3001';
156
16−const reqHandler = (resolve, reject) => {
17− return (response) => {
18− console.log('xx got response', response)
19− // handle http errors
20− if (response.statusCode < 200 || response.statusCode > 299) {
21− reject(new Error('Failed to load, status code: ' + response.statusCode));
22− }
23− // temporary data holder
24− const body = [];
25− // on every content chunk, push it to the data array
26− response.on('data', (chunk) => body.push(chunk));
27− // we are done, resolve promise with those joined chunks
28− response.on('end', () => {
29− return resolve(JSON.parse(body.join('')))
30− });
31− }
7+function sendRequest(where, what) {
8+ return new Promise((resolve, reject) => {
9+ fetch(baseUrl + where, {
10+ method: 'POST',
11+ cache: 'no-cache',
12+ headers: {
13+ 'Content-Type': 'application/json'
14+ },
15+ body: JSON.stringify(what)
16+ })
17+ .then(response => {
18+ if (response.ok) {
19+ resolve(response.json());
20+ } else {
21+ reject(response);
22+ }
23+ })
24+ .catch(reject);
25+ });
3226}
3327
3428const remainingTransactions = point => {
35− return new Promise((resolve, reject) => {
36− const options = {
37− path: '/point',
38− method: 'POST'
39− }
40− const request = http.request(
41− Object.assign(baseOptions, options),
42− reqHandler(resolve, reject)
43− );
44− request.on('error', (e) => reject(new Error(e)));
45− request.write(JSON.stringify({point:point}));
46− request.end();
47− });
29+ return sendRequest('/point', {point:point});
4830};
4931
50−//TODO refactor, add sendRequest(path, json)
5132const fundTransactions = signedTxs => {
52− return new Promise((resolve, reject) => {
53− const options = {
54− path: '/request',
55− method: 'POST'
56− }
57− const request = http.request(
58− Object.assign(baseOptions, options),
59− reqHandler(resolve, reject)
60− );
61− request.on('error', (e) => reject(new Error(e)));
62− request.write(JSON.stringify({txs:signedTxs}));
63− request.end();
64− });
33+ return sendRequest('/request', {txs:signedTxs});
6534};
6635
6736export {