Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created February 17, 2021 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecademydev/2b8f6adf50a27f53b984603efca0d255 to your computer and use it in GitHub Desktop.
Save codecademydev/2b8f6adf50a27f53b984603efca0d255 to your computer and use it in GitHub Desktop.
Codecademy export
// Manipulates responseField to render a formatted and appropriate message
const renderResponse = (res) => {
// Displays either message depending on results
if(res.errors){
responseField.innerHTML = "<p>Sorry, couldn't format your URL.</p><p>Try again.</p>";
} else {
responseField.innerHTML = `<p>Your shortened url is: </p><p> ${res.shortUrl} </p>`;
}
}
// Manipulates responseField to render an unformatted response
const renderRawResponse = (res) => {
// Displays either message depending on results
if(res.errors){
responseField.innerHTML = "<p>Sorry, couldn't format your URL.</p><p>Try again.</p>";
} else {
// Adds line breaks for JSON
let structuredRes = JSON.stringify(res).replace(/,/g, ", \n");
structuredRes = `<pre>${structuredRes}</pre>`;
responseField.innerHTML = `${structuredRes}`;
}
}
// Renders the JSON that was returned when the Promise from fetch resolves.
const renderJsonResponse = (response) => {
// Creates an empty object to store the JSON in key-value pairs
let rawJson = {}
for(let key in response){
rawJson[key] = response[key]
}
// Converts JSON into a string and adding line breaks to make it easier to read
rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n")
// Manipulates responseField to show the returned JSON.
responseField.innerHTML = `<pre>${rawJson}</pre>`
}
// Information to reach API
const apiKey = '1582a064d105495a90c39707fe9e4b39';
const url = 'https://api.rebrandly.com/v1/links';
// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');
// AJAX functions
const shortenUrl = () => {
const urlToShorten = inputField.value;
const data = JSON.stringify({destination: urlToShorten});
fetch(url, {method: 'POST', headers: {
'Content-type': 'application/json',
'apikey': apiKey
}, body: data}).then(response => {
if(response.ok) {
return response.json()
}
throw new Error('Request failed!')
}, networkError => {
console.log(networkError.message)
}).then(jsonResponse => {
renderResponse(jsonResponse)
})
}
// Clear page and call AJAX functions
const displayShortUrl = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild)
}
shortenUrl();
}
shortenButton.addEventListener('click', displayShortUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment