fix: sort by date function Entries

This commit is contained in:
Thomas Bishop 2025-07-22 15:57:16 +01:00
parent 681350e6f7
commit c4fb0525a9
2 changed files with 23 additions and 9 deletions

View file

@ -1,11 +1,13 @@
import express from "express" import express from "express"
import entries from "./routes/entries.js" import entries from "./routes/entries.js"
import tags from "./routes/tags.js" import tags from "./routes/tags.js"
import cors from "cors"
const app = express() const app = express()
const port = process.env.PORT || 3000 const port = process.env.PORT || 3000
app.use(cors())
app.use(express.json()) app.use(express.json())
app.use("/entries", entries) app.use("/entries", entries)
app.use("/tags", tags) app.use("/tags", tags)

View file

@ -12,14 +12,14 @@ export default class EntriesService {
} }
getAllEntries = (sort, limit) => { getAllEntries = (sort, limit) => {
const entries = this.database const entries = this.database.prepare(GET_ALL_ENTRIES).all()
.prepare(GET_ALL_ENTRIES)
.all() const sorted =
.slice(0, Number(limit) || -1) sort === "date" ? this._sortByDate(entries) : this._sortByTitle(entries, "title")
return { return {
count: entries.length, count: entries.length,
entries: sort === "date" ? this._sortByDate(entries) : this._sortByTitle(entries, "title"), entries: sorted.slice(0, Number(limit) || -1),
} }
} }
@ -27,7 +27,10 @@ export default class EntriesService {
const entries = this.database.prepare(GET_ENTRIES_FOR_TAG).all(tag) const entries = this.database.prepare(GET_ENTRIES_FOR_TAG).all(tag)
return { return {
count: entries.length, count: entries.length,
entries: sort === "date" ? this._sortByDate(entries) : this._sortByTitle(entries, "entry_title"), entries:
sort === "date"
? this._sortByDate(entries)
: this._sortByTitle(entries, "entry_title"),
} }
} }
@ -35,7 +38,16 @@ export default class EntriesService {
return entries.sort((a, b) => a[fieldName].localeCompare(b[fieldName])) return entries.sort((a, b) => a[fieldName].localeCompare(b[fieldName]))
} }
_sortByDate = (entries, fieldName = last_modified) => { _sortByDate = (entries, fieldName = "last_modified") => {
return entries.sort((a, b) => new Date(b[fieldName]) - new Date(a[fieldName])) console.log(
"Before sort:",
entries.slice(0, 2).map((e) => e.last_modified),
)
const sorted = entries.sort((a, b) => new Date(b[fieldName]) - new Date(a[fieldName]))
console.log(
"After sort:",
sorted.slice(0, 2).map((e) => e.last_modified),
)
return sorted
} }
} }