Skip to content

Commit

Permalink
Add author parameter to query and implement quote filtering by author (
Browse files Browse the repository at this point in the history
  • Loading branch information
marceloams committed Oct 13, 2024
1 parent bceb0a9 commit 3930648
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/api/controllers/quotesController.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,17 @@ const quoteController = async (req, res, next) => {

let quoteType = req.query.quoteType || '';

let author = req.query.author || undefined;

let quoteObject = {
theme,
animation,
layout,
quotesUrl,
quoteCategory,
font,
quoteType
quoteType,
author
}


Expand Down
23 changes: 22 additions & 1 deletion src/api/services/quotesService.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,16 @@ getQuoteIndex = (apiResponseLength, quoteType) => {
return (quoteType === "quote-for-the-day" ? epoch % apiResponseLength : Math.random() * apiResponseLength);
}

const filterQuotesByAuthor = (quotes, author) => {
const quotesFiltered = quotes.filter((quote) => quote?.author?.toString().toLowerCase().trim() === author.toString().toLowerCase().trim());

return quotesFiltered.length > 0 ? quotesFiltered : quotes;
}

const getQuote = async (quoteObj) => {

try {
let { theme, animation, layout, quotesUrl, quoteCategory, font, quoteType } = quoteObj;
let { theme, animation, layout, quotesUrl, quoteCategory, font, quoteType, author } = quoteObj;
let apiResponse;
let { customQuotesUrl, isValidUrl } = await getValidUrl(quotesUrl);
let isCustomQuote = false;
Expand All @@ -24,6 +30,10 @@ const getQuote = async (quoteObj) => {
//url from params is valid, proceed to verfiy the data
apiResponse = await requestApi(customQuotesUrl);

if (author) {
apiResponse = filterQuotesByAuthor(apiResponse, author);
}

if (apiResponse.length > 0) {
apiResponse = apiResponse[Math.floor(getQuoteIndex(apiResponse.length, quoteType))];

Expand All @@ -34,12 +44,23 @@ const getQuote = async (quoteObj) => {
}
else if (quoteCategory) {
apiResponse = quoteFromCategory[quoteCategory];

if (author) {
apiResponse = filterQuotesByAuthor(apiResponse, author);
}

apiResponse = apiResponse[Math.floor(getQuoteIndex(apiResponse.length, quoteType))];

isCustomQuote = true;
}

if(!isCustomQuote) {
apiResponse = await requestApi(url);

if (author) {
apiResponse = filterQuotesByAuthor(apiResponse, author);
}

apiResponse = apiResponse[Math.floor(getQuoteIndex(apiResponse.length, quoteType))];
}

Expand Down

0 comments on commit 3930648

Please sign in to comment.