Skip to content

Commit

Permalink
Implement endpoint to retrieve a sorted list of unique authors. Added…
Browse files Browse the repository at this point in the history
… support for filtering by quoteCategory. (#131)
  • Loading branch information
marceloams committed Dec 4, 2024
1 parent 472893b commit 6b736e6
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/api/controllers/authorsController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const quoteService = require("../services/quotesService");

const authorsController = async (req, res, next) => {

try {

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

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

let quoteObject = {
quotesUrl,
quoteCategory,
}

const authors = await quoteService.getAuthors(quoteObject);

res.setHeader("Content-Type", "application/json");

res.header(
"Cache-Control",
"no-cache,max-age=0,no-store,s-maxage=0,proxy-revalidate"
);
res.header("Pragma", "no-cache");
res.header("Expires", "-1");
res.json(authors);

} catch (error) {
console.error(error);
res.send({
name: error.name,
message: error.message,
});
}
};

module.exports = {
authorsController
};
4 changes: 4 additions & 0 deletions src/api/routes/quotes-router.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,16 @@


const controllers = require('../controllers/quotesController');
const authorsController = require('../controllers/authorsController');

const defineRoutes = (app) => {

// get a quote
app.get('/quote', controllers.quoteController);

// get authors
app.get('/authors', authorsController.authorsController);

}

module.exports = defineRoutes;
40 changes: 40 additions & 0 deletions src/api/services/quotesService.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,46 @@ const getQuote = async (quoteObj) => {
}
};

const getAuthors = async (quoteObj) => {
try {
let {quotesUrl, quoteCategory} = quoteObj;
let apiResponse;
let { customQuotesUrl, isValidUrl } = await getValidUrl(quotesUrl);
let isCustomQuote = false;

if (isValidUrl) {
//url from params is valid, proceed to verfiy the data
apiResponse = await requestApi(customQuotesUrl);

if (apiResponse.length > 0) {
if (apiResponse[0].author) {
isCustomQuote = true;
}
}
}
else if (quoteCategory) {
apiResponse = quoteFromCategory[quoteCategory];
isCustomQuote = true;
}

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

if (!apiResponse || apiResponse.length === 0) {
return [];
}

// Get array of authors in alphabetical order and without duplicates
const authors = [...new Set(apiResponse.map(quote => quote.author).sort())];

return authors;
} catch (error) {
throw error;
}
}

module.exports = {
getQuote,
getAuthors
};

0 comments on commit 6b736e6

Please sign in to comment.