Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
dynamic-websites/exercises/05_client/api_client/script.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
65 lines (58 sloc)
1.97 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const baseURL = 'https://api.exchangeratesapi.io/latest' | |
document.addEventListener('DOMContentLoaded', async() => { | |
console.log('page loaded') | |
await createDropdown() | |
document.querySelector('select[name="base"]').onchange = getRates | |
}) | |
// populates the currency dropdown with a list of currency codes. | |
async function createDropdown() { | |
const data = await makeRequest(`${baseURL}`) | |
data.rates.EUR = 1.0 | |
const select = document.querySelector('select[name="base"]') | |
Object.keys(data.rates).sort().forEach( val => { | |
const node = document.createElement('option') | |
node.appendChild(document.createTextNode(val)) | |
select.appendChild(node) | |
}) | |
} | |
// retrieves the value from the dropdown options list | |
async function getRates() { | |
const e = document.querySelector('select[name="base"]') | |
const base = e.options[e.selectedIndex].value | |
const table = document.querySelector('table') | |
table.innerHTML = '' | |
if(base) { | |
document.querySelector('h2').innerHTML = `Base Currency: ${base}` | |
const data = await makeRequest(`${baseURL}?base=${base}`) | |
buildTable(data.rates) | |
} | |
} | |
// creates a new html table with the data from the parameter | |
function buildTable(rates) { | |
const table = document.querySelector('table') | |
Object.keys(rates).sort().forEach( val => { | |
if(rates[val] !== 1) { | |
const row = table.insertRow(-1) | |
row.insertCell(0).innerHTML = val | |
row.insertCell(1).innerHTML = rates[val] | |
} | |
}) | |
} | |
// this function converts the standard XMLHTTPRequest to a promise | |
const makeRequest = (url, method = 'GET') => new Promise( (resolve, reject) => { | |
const ok = 2 | |
const percent = 100 | |
const xhr = new XMLHttpRequest() | |
xhr.open(method, url) | |
xhr.onload = function() { | |
if ( Math.floor(this.status/percent) !== ok) { // if response code does not start with 2 | |
return reject({status: this.status, statusText: xhr.statusText }) | |
} | |
return resolve(JSON.parse(xhr.response)) | |
} | |
xhr.onerror = function() { | |
return reject({ status: this.status, statusText: xhr.statusText }) | |
} | |
xhr.send() | |
}) |