Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created April 22, 2020 20:39
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/3f97ced200940abeabcef8404924db9a to your computer and use it in GitHub Desktop.
Save codecademydev/3f97ced200940abeabcef8404924db9a to your computer and use it in GitHub Desktop.
Codecademy export
const submitButton = document.getElementById('submit-quote');
const deletedQuoteContainer = document.getElementById('deleted-quote');
submitButton.addEventListener('click', () => {
const quoteId = document.getElementById('quote-id').value;
fetch(`/api/quotes/${quoteId}`, { method: 'DELETE' })
.then(response => {
console.log(response)
return response.json()
})
.then(({ quote }) => {
console.log(quote)
const deletedQuote = document.createElement('div');
deletedQuote.innerHTML = `
<h3>'You deleted this Quote correctly! 🤙'</h3>
<div class="quote-text">${quote.quote}</div>
<div class="attribution">- ${quote.person}</div>
<p>Go to the <a href="index.html">home page</a> to request and view all quotes.</p>
`
deletedQuoteContainer.appendChild(deletedQuote);
});
});
const express = require('express');
const fetch = require('node-fetch');
const app = express();
const { quotes } = require('./data');
const { getRandomElement, generateIds, getIndexById } = require('./utils');
const PORT = process.env.PORT || 4001;
app.use(express.static('public'));
// Get routes - get data from quotes array
app.get('/api/quotes', (req, res) => {
let quoteMatch;
let quoteSearch = req.query.person;
if (quoteSearch == undefined) {
res.send({quotes: quotes})
} else {
quotesMatch = quotes.filter(quote => {
return quote.person == quoteSearch && quote;
});
if (quoteMatch) {
res.send({ quotes: quotesMatch });
} else {
res.status(404).send('Author not found!! 😡');
}
}
})
app.get('/api/quotes/random', (req, res) => {
let randomQuote = getRandomElement(quotes);
res.send({quote: randomQuote})
})
// Post route - add new quotes to the array
app.post('/api/quotes', (req, res) => {
let newQuotePerson = req.query.person;
let newQuote = req.query.quote;
if (newQuote && newQuotePerson) {
quotes.push(req.query);
generateIds(quotes);
getPersonInfo(quotes);
res.status(201).send({quote: quotes[quotes.length-1]});
} else {
res.status(400).send('Quote not found with the id provided! 🤷‍♂️');
}
})
// Put route - update the data in the array (based on id provided)
app.put('/api/quotes/:id', (req, res) => {
// first we check if there're not missing parameter in the request
if (req.query.person && req.query.quote) {
const quoteIndex = getIndexById(req.params.id, quotes);
// check if there is a match using the id provided in the request
if (quoteIndex !== -1) {
quotes[quoteIndex] = req.query
getPersonInfo(quotes);
res.send({ quote: req.query });
} else {
res.status(404).send('Quote not found with the id provided! 🤷‍♂️')
}
} else {
res.status(400).send("There's a missing parameter in the request!")
}
})
// Delete route - handle the delete requests
app.delete('/api/quotes/:id', (req, res) => {
const quoteIndex = getIndexById(req.params.id, quotes);
if (quoteIndex !== -1) {
quotes.splice(quoteIndex, 1);
res.send({ quote: quotes[quoteIndex] });
} else {
res.status(404).send('Quote not found with the id provided! 🤷‍♂️')
}
})
const getPersonInfo = (arr) => {
// for each element it will make a Get request to the Wikipedia Api with a Title parameter as the value of quotes.person
// this GET request will get us a Json with just a short description about the person we have searched.
arr.forEach(quote => {
// we make the request just if the property description doesn't exist yet
if (!quote.description) {
fetch(`https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=${quote.person}`)
.then(response => {
return response.json()
})
.then(jsonResponse => {
// this part looks a bit ugly but it's the only way i found to get that description .
//(it's a bit nested and at some point the property name is a string which is different in each request)
let pageInfo = jsonResponse.query.pages;
Object.keys(pageInfo).forEach(item => {
quote.description = pageInfo[item].extract;
});
})
.catch(error => {
console.log(error)
quote.description = 'No Description Avilable 😢'
})
}
})
}
app.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
// asign an id for all the quotes aready in the array
generateIds(quotes);
// each time the server is started it will get the biographical blurbs for all the person
getPersonInfo(quotes);
})
const submitButton = document.getElementById('submit-quote');
const updatedQuoteContainer = document.getElementById('updated-quote');
submitButton.addEventListener('click', () => {
const quote = document.getElementById('quote').value;
const person = document.getElementById('person').value;
const quoteId = document.getElementById('quote-id').value;
fetch(`/api/quotes/${quoteId}?quote=${quote}&person=${person}`, {method: 'PUT'})
.then(response => response.json())
.then(({ quote }) => {
console.log(quote)
const updatedQuote = document.createElement('div');
updatedQuote.innerHTML = `
<h3>Congrats, your quote was updated correctly!</h3>
<div class="quote-text">${quote.quote}</div>
<div class="attribution">- ${quote.person}</div>
<p>Go to the <a href="index.html">home page</a> to request and view all quotes.</p>
`
updatedQuoteContainer.appendChild(updatedQuote);
});
});
const getRandomElement = arr => {
if (!Array.isArray(arr)) throw new Error('Expected an array');
return arr[Math.floor(Math.random() * arr.length)];
}
const generateIds = arr => {
arr.forEach((quote, index) => {
// create a property of id just if it doesn't exist already (once the ids are generated won't be changed)
quote.id = !quote.id && `quote${index + 1}`;
});
}
const getIndexById = (id, arr) => {
return arr.findIndex((quote) => {
// return the index if the there is a match
return quote.id == id;
});
};
const getPersonInfo = (person, arr) => {
fetch(`https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=${person}`)
.then(response => {
arr.newLine = response
}, rejected => {
return false
})
}
module.exports = { getRandomElement, generateIds, getIndexById }
@mazelos
Copy link

mazelos commented Apr 23, 2020

I still don't get why gives me an error on line 91-93 in server.js if i write it like this:

 quote.description = jsonResponse.query.pages[0].extract

or even like this :

let pageInfo = jsonResponse.query.pages;
pageInfo.forEach(item => {
     quote.description = item.extract;
}

instead i had to write it in this way (as you can see in the file):

let pageInfo = jsonResponse.query.pages;
Object.keys(pageInfo).forEach(item => {
quote.description = pageInfo[item].extract;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment