Chingu FCC Speedrun Challenge: Local Weather

Amir Fakheraldeen
Chingu FCC Speedrun
2 min readMay 10, 2017

My third project in the speedrun went pretty smoothly in relation to the previous one (random quote machine).

The idea of the project is to show the current weather based on the user’s location. For this, I wrote two modules: one to handle getting the location of the user, and another to handle getting the weather based on the location. I chose to use IP-API to retrieve the location, and the OpenWeatherMap API to retrieve the current weather. The latter API request is dependent on the first, so I chose to use Promises in order to make the requests in the correct order, making the second request only when the first has returned a response. I also got to use the AJAX utility I had originally written for the previous project (if you’ve read my post about the random quote machine you’ll know why I didn’t get to use it on that project).

The reason I wrote my own AJAX utility is because I wanted something that’s based on Promises, and also to practice JavaScript more. The utility is pretty simple, here it is in its entirety:

export default class Ajax {
static resolveUrl(url, params) {
let paramsKeys = Object.keys(params);
// check if params were provided
if (paramsKeys.length > 0) {
url += "?";
// attach params to the url
for (let param of paramsKeys) {
url += `${param}=${params[param]}`;
// add a "&" as long as it's not the last param
if (param !== paramsKeys[paramsKeys.length - 1]) {
url += "&";
}
}
}
return url;
}
static get(url, params = {}) {
url = this.resolveUrl(url, params);
return new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.responseText);
}
else {
reject(xhr.status);
}
}
};
xhr.open("GET", url, true);
xhr.send(null);
});
}
}

Nothing too fancy, just a basic GET request handler. This is how I used it with the location module I talked about above for example:

import Ajax from "./ajax";class Location {
constructor(city, region, country) {
this.city = city || "Unknown city";
this.region = region || "Unknown region";
this.country = country;
}
}
export default class Geo {
static getLocation() {
return new Promise(function(resolve, reject) {
let url = "http://ip-api.com/json";
Ajax.get(url).then(
function fulfilled(response) {
response = JSON.parse(response);
resolve(new Location(
response.city,
response.regionName,
response.country
));
},
function rejected(reason) {
reject(reason);
});
});
}
}

Links:

Other projects built as part of the challenge:

--

--