Skip to content

Commit

Permalink
Add request module,
Browse files Browse the repository at this point in the history
> add config.js file and include in .gitignore
write API request in api.js to weather API

co-authored-by: Rosa <[email protected]>
relates #2
  • Loading branch information
plasticneuron committed Nov 27, 2019
1 parent a8c1bd6 commit 165a142
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules
.nyc_output
.ds_store
npm-debug.log
src/config.js
16 changes: 16 additions & 0 deletions src/api.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,18 @@
const http = require("http");
const https = require("https");
const requester = require("./request");
const config = require('./config');

// grab api key from local config file
let apiKey = config.MY_WEATHER_KEY;

// initialise test city and country (later provided by GET request from frontend)
let city = 'London';
let country = 'uk';

const weather = requester(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=${apiKey}", (err, res) => {
if (err) throw new Error(`Weather API failed. Error: ${err}`);
console.log(res.body);
return res.body;
}
);
52 changes: 52 additions & 0 deletions src/request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"use strict";

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

const requester = (url, cb) => {
/^https/.test(url) ? get(https, url, cb) : get(http, url, cb);
};

const get = (protocol, url, cb) => {
protocol.get(url, res => {
// initialise variables to pass to callback
let err;
let resObj = {};

// non-stream related error handling
const { statusCode } = res;
const contentType = res.headers["content-type"];
if (statusCode !== 200) {
err = new Error(`Your request has failed. Status code: ${statusCode}`);
cb(err);
} else if (!/json/.test(contentType)) {
err = new Error(
`Unexpected content type: expecting JSON but received ${contentType}`
);
cb(err);
}

// stream the body of the response
res.setEncoding("utf8");
let rawData = "";
res.on("data", chunk => {
rawData += chunk;
});

// handle errors occuring during streaming
res.on("error", e => {
err = e;
cb(err);
});

// on successful stream, pass constructed response object to callback
res.on("end", () => {
resObj.body = JSON.parse(rawData);
resObj.statusCode = statusCode;
console.log(resObj);
cb(null, resObj);
});
});
};

module.exports = requester;

0 comments on commit 165a142

Please sign in to comment.