Browse Source

Add route /article/:slug

Request an article by its unique slug and receive a JSON response.
master
Perception 2 months ago
parent
commit
96a46e85d6
2 changed files with 42 additions and 0 deletions
  1. +25
    -0
      index.js
  2. +17
    -0
      routes/article/:slug.js

+ 25
- 0
index.js View File

@ -278,6 +278,16 @@ async function getCategories(db) {
return cats2
}
async function getCategoriesForArticle(db, id) {
const categories = db.prepare(`
SELECT c.name
FROM category c
JOIN article__category ac ON ac.category_id = c.id
WHERE ac.article_id = @id
`).all({ id }).map((c) => c.name)
return categories
}
async function getTagCloud(db, limit, offset=0) {
const tags = db.prepare(`
SELECT name, c FROM (
@ -293,6 +303,19 @@ async function getTagCloud(db, limit, offset=0) {
return tags
}
// SECTION: Articles
async function getArticleBySlug(db, slug) {
const article = db.prepare('SELECT * FROM article WHERE slug = @slug').get({ slug })
if (article) {
const tagsById = await getTagsForArticles(db, [ article.id ])
article.tags = tagsById[article.id]
article.categories = await getCategoriesForArticle(db, article.id)
delete article.year_month
}
return article
}
// SECTION: Archives
async function getArticleCounts(db, year) {
@ -464,6 +487,7 @@ module.exports = {
articleExists,
fetchArticle,
getCategory,
getCategoriesForArticle,
getTag,
assocCategory,
assocTag,
@ -475,6 +499,7 @@ module.exports = {
getYears,
getCategories,
getTagCloud,
getArticleBySlug,
getArticleCounts,
getArticlesByYearMonth,
getArticlesByCategory,


+ 17
- 0
routes/article/:slug.js View File

@ -0,0 +1,17 @@
const { send, json } = require('micro')
const Database = require('better-sqlite3')
const page = require('../../page')
const ds = require('../../index')
const db = ds.db()
module.exports.GET = async (req, res) => {
let _slug = req.params.slug
let slug = `/${_slug}/`
let article = await ds.getArticleBySlug(db, slug)
if (article) {
send(res, 200, article)
} else {
send(res, 404, { message: 'Article Not Found', slug: _slug })
}
}

Loading…
Cancel
Save