From 254c5be8f5b4cbc38da25f777101c49e9bbf481c Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Thu, 17 Jul 2025 17:57:11 +0100 Subject: [PATCH] feat: add get_all_entries_for_tag method --- src/controllers/EntriesController.js | 12 ++++++++++++ src/routes/entries.js | 2 +- src/services/EntriesService.js | 18 +++++++++++++++++- src/sql/entries.js | 4 +++- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/controllers/EntriesController.js b/src/controllers/EntriesController.js index fecdd88..3c85684 100644 --- a/src/controllers/EntriesController.js +++ b/src/controllers/EntriesController.js @@ -28,4 +28,16 @@ export default class EntriesController { return res.json(entries) } + + getEntriesForTag = (req, res) => { + const tag = req.params.tag + const sort = req.query.sort + const entries = this.entriesService.getEntriesForTag(tag, sort) + if (!entries) { + return res.status(404).json({ + message: `Could not retrieve entries for tag ${tag}`, + }) + } + return res.json(entries) + } } diff --git a/src/routes/entries.js b/src/routes/entries.js index b5652af..bf486b6 100644 --- a/src/routes/entries.js +++ b/src/routes/entries.js @@ -9,5 +9,5 @@ const entriesController = new EntriesController(entriesService) router.get("/", entriesController.getAllEntries) router.get("/:title", entriesController.getEntry) - +router.get("/tag/:tag", entriesController.getEntriesForTag) export default router diff --git a/src/services/EntriesService.js b/src/services/EntriesService.js index d65b51d..5c51699 100644 --- a/src/services/EntriesService.js +++ b/src/services/EntriesService.js @@ -1,5 +1,5 @@ import { sortByDate, sortByTitle } from "../lib/sorters.js" -import { GET_ALL_ENTRIES, GET_ENTRY } from "../sql/entries.js" +import { GET_ALL_ENTRIES, GET_ENTRY, GET_ENTRIES_FOR_TAG } from "../sql/entries.js" export default class EntriesService { database @@ -23,4 +23,20 @@ export default class EntriesService { entries: sort === "date" ? sortByDate(entries) : sortByTitle(entries), } } + + getEntriesForTag = (tag, sort) => { + const entries = this.database.prepare(GET_ENTRIES_FOR_TAG).all(tag) + return { + count: entries.length, + entries: sort === "date" ? this._sortByDate(entries) : this._sortByTitle(entries, "entry_title"), + } + } + + _sortByTitle = (entries, fieldName) => { + return entries.sort((a, b) => a[fieldName].localeCompare(b[fieldName])) + } + + _sortByDate = (entries, fieldName = last_modified) => { + return entries.sort((a, b) => new Date(b[fieldName]) - new Date(a[fieldName])) + } } diff --git a/src/sql/entries.js b/src/sql/entries.js index a5f1709..9272547 100644 --- a/src/sql/entries.js +++ b/src/sql/entries.js @@ -2,4 +2,6 @@ const GET_ENTRY = `SELECT * FROM entries WHERE title = ?` const GET_ALL_ENTRIES = `SELECT title, last_modified FROM entries` -export { GET_ENTRY, GET_ALL_ENTRIES } +const GET_ENTRIES_FOR_TAG = `SELECT entry_title from entries_tags WHERE tag_name = ?` + +export { GET_ENTRY, GET_ALL_ENTRIES, GET_ENTRIES_FOR_TAG }