-
-
Save codecademydev/f98bb7b896b17c36e1f2c0853c0c74bd to your computer and use it in GitHub Desktop.
Codecademy export
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
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