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 Dec 4, 2024
1 parent d8d23d8 commit 472893b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/api/controllers/quotesController.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ const quoteController = async (req, res, next) => {

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

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

let quoteObject = {
theme,
animation,
Expand All @@ -42,6 +44,7 @@ const quoteController = async (req, res, next) => {
quoteCategory,
font,
quoteType,
author,
borderColor
}

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, borderColor } = quoteObj;
let { theme, animation, layout, quotesUrl, quoteCategory, font, quoteType, borderColor, 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 472893b

Please sign in to comment.