Skip to content

Commit

Permalink
fix: not fetching properly
Browse files Browse the repository at this point in the history
  • Loading branch information
TobiTenno committed Nov 19, 2018
1 parent 1cb6f4b commit 6b68e7d
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/WorldStateCache.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
'use strict';

const https = require('https');
const http = require('http');

const fetch = require('node-fetch');

const EventEmitter = require('events');
Expand Down Expand Up @@ -36,7 +39,7 @@ class WorldStateCache extends EventEmitter {

async update() {
try {
const data = await fetch(this.url).then(res => res.json());
const data = await this.httpGet();
this.lastUpdated = Date.now();
delete this.currentData;
this.currentData = JSON.parse(data);
Expand All @@ -49,6 +52,21 @@ class WorldStateCache extends EventEmitter {
}
return this.updating;
}

httpGet() {
return new Promise((resolve, reject) => {
const protocol = this.url.startsWith('https') ? https : http;
const request = protocol.get(this.url, (response) => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`Failed to load page ${this.url}, status code: ${response.statusCode}`));
}
const body = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => resolve(body.join('')));
});
request.on('error', err => reject(err));
});
}
}

module.exports = WorldStateCache;

0 comments on commit 6b68e7d

Please sign in to comment.