Skip to content

Commit

Permalink
#2 implementation of identity map
Browse files Browse the repository at this point in the history
  • Loading branch information
pbgnz committed Mar 29, 2021
1 parent 8d201b6 commit 41e4b37
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 18 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "random-quote-api",
"version": "1.1.1",
"version": "1.2.1",
"description": "get random quotes",
"main": "server.js",
"scripts": {
Expand Down
43 changes: 26 additions & 17 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,34 @@ const port = process.env.PORT || 8000;
app.use(express.json());
app.use(router);

let identityMap = new Map();

router.get('/api/quotes', (req, res) => {
let pageNumber = Math.floor(Math.random() * 100) + 1;
let quotes = [];
request('https://www.goodreads.com/quotes?page=' + pageNumber, function (err, r, body) {
if (err) {
res.send("401: Error getting quotes");
} else {
let $ = cheerio.load(body);
$('div.quoteText').each(function (index) {
const quote = $(this)[0].children[0].data.replace(/(\r\n|\n|\r| +(?= )| “|”)/gm, "");
const id = index;
quotes.push({ quote, id });
});
$('span.authorOrTitle').each(function (index) {
quotes[index].author = $(this)[0].children[0].data.replace(/(\r\n|\n|\r| +(?= )|,)/gm, "");
});
res.send({ quotes });
}
});

if (identityMap.has(pageNumber)) {
const quotes = identityMap.get(pageNumber);
res.send({ quotes });
} else {
let quotes = [];
request('https://www.goodreads.com/quotes?page=' + pageNumber, function (err, r, body) {
if (err) {
res.send("401: Error getting quotes");
} else {
let $ = cheerio.load(body);
$('div.quoteText').each(function (index) {
const quote = $(this)[0].children[0].data.replace(/(\r\n|\n|\r| +(?= )| “|”)/gm, "");
const id = index;
quotes.push({ quote, id });
});
$('span.authorOrTitle').each(function (index) {
quotes[index].author = $(this)[0].children[0].data.replace(/(\r\n|\n|\r| +(?= )|,)/gm, "");
});
identityMap.set(pageNumber, quotes);
res.send({ quotes });
}
});
}
});

app.listen(port);
Expand Down

0 comments on commit 41e4b37

Please sign in to comment.