Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created April 5, 2023 14:19
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/b73910c07efbe73d8df79a0d43c31ae4 to your computer and use it in GitHub Desktop.
Save codecademydev/b73910c07efbe73d8df79a0d43c31ae4 to your computer and use it in GitHub Desktop.
Codecademy export
const express = require("express");
const app = express();
const { quotes } = require("./data");
const { getRandomElement } = require("./utils");
const PORT = process.env.PORT || 4001;
app.use(express.static("public"));
app.listen(PORT, () => {
console.log("server listening at port " + PORT);
});
app.get("/api/quotes/random", (req, res, next) => {
console.log("requesting random quote");
const quoteRandom = getRandomElement(quotes);
res.json({ quote: quoteRandom });
console.log("sent ", { quote: quoteRandom }, "\n");
next();
});
app.get("/api/quotes", (req, res, next) => {
let author = req.query.person;
const persons = quotes.map((obj) => obj.person.toLowerCase());
const arr = Object.keys(req.query);
if (arr.length === 0) {
//send all if no query provided
res.json({ quotes: quotes });
console.log("request all quotes and sent. \n");
} else if (persons.includes(author.toLowerCase())) {
// send selected person quotes
const selectedPersonQuotes = quotes.filter(
(ele) => ele.person.toLowerCase() === author.toLowerCase()
);
res.json({ quotes: selectedPersonQuotes });
console.log("request quotes of " + author + ", sent \n");
} else {
res.status(404).send("person not found");
console.log("request quotes of " + author + ", author not found \n");
}
next();
});
app.post("/api/quotes", (req, res) => {
const queryObj = req.query;
console.log("receive post request, req.query is ", queryObj);
if (queryObj.person && queryObj.quote) {
const itemToAdd = {
quote: queryObj.quote,
person: queryObj.person,
};
quotes.push(itemToAdd);
res.json({
quote: itemToAdd,
});
console.log("sent\n");
} else {
console.log("400\n");
res.status(400).send("query not completed");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment