Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created August 4, 2020 13:24
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/f98bb7b896b17c36e1f2c0853c0c74bd to your computer and use it in GitHub Desktop.
Save codecademydev/f98bb7b896b17c36e1f2c0853c0c74bd to your computer and use it in GitHub Desktop.
Codecademy export
const express = require('express');
const morgan = require('morgan');
const app = express();
const { quotes } = require('./data');
const { getRandomElement } = require('./utils');
const PORT = process.env.PORT || 4001;
app.use(express.static('public'));
//Random quote (GET)//
app.get('/api/quotes/random', (req, res, next) => {
res.send({quote: getRandomElement(quotes)})
});
//All quotes or By author (GET)//
app.get('/api/quotes', (req, res, next) => {
if (req.query.person !== undefined){
const byAuthor = quotes.filter(quote => quote.person === req.query.person);
res.send({quotes: byAuthor});
} else {
res.send({quotes});
}
});
//Add new quote (POST) //
app.post('/api/quotes', (req, res, next) => {
const newObj = {
quote: req.query.quote,
person: req.query.person
};
if (newObj.quote && newObj.person){
console.log(newObj);
quotes.push(newObj);
res.send({quote: newObj});
} else {
console.log('failed')
res.status(400).send();
}
})
app.listen(PORT, () => {
console.log(`Server listening to port ${PORT}`)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment