| 1 | /**
|
|---|
| 2 | * GET /tag/:tag
|
|---|
| 3 | *
|
|---|
| 4 | * Lists published posts on the current site that contain :tag in their
|
|---|
| 5 | * tags JSON array. Uses SQLite's json_each() to expand the array.
|
|---|
| 6 | */
|
|---|
| 7 |
|
|---|
| 8 | import express from 'express';
|
|---|
| 9 | import db from '../config/database.js';
|
|---|
| 10 | import { renderPage } from '../middleware/render.js';
|
|---|
| 11 |
|
|---|
| 12 | const router = express.Router();
|
|---|
| 13 |
|
|---|
| 14 | router.get('/:tag', (req, res) => {
|
|---|
| 15 | const site = res.locals.site;
|
|---|
| 16 | if (!site) return res.status(404).send('No site');
|
|---|
| 17 |
|
|---|
| 18 | const tag = (req.params.tag || '').trim();
|
|---|
| 19 | if (!tag) return res.redirect(res.locals.siteUrlBase || '/');
|
|---|
| 20 |
|
|---|
| 21 | let posts = [];
|
|---|
| 22 | try {
|
|---|
| 23 | posts = db.prepare(`
|
|---|
| 24 | SELECT DISTINCT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.cover_video_url,
|
|---|
| 25 | p.published_at, u.username AS author_username
|
|---|
| 26 | FROM posts p, json_each(p.tags) j
|
|---|
| 27 | JOIN users u ON u.id = p.author_id
|
|---|
| 28 | WHERE p.site_id = ?
|
|---|
| 29 | AND p.status = 'published'
|
|---|
| 30 | AND j.value = ?
|
|---|
| 31 | ORDER BY p.published_at DESC
|
|---|
| 32 | LIMIT 100
|
|---|
| 33 | `).all(site.id, tag);
|
|---|
| 34 | } catch (e) {
|
|---|
| 35 | // Fall back to a LIKE match if json_each isn't available for some reason
|
|---|
| 36 | posts = db.prepare(`
|
|---|
| 37 | SELECT p.id, p.slug, p.title, p.excerpt, p.cover_image_url, p.cover_video_url,
|
|---|
| 38 | p.published_at, u.username AS author_username
|
|---|
| 39 | FROM posts p JOIN users u ON u.id = p.author_id
|
|---|
| 40 | WHERE p.site_id = ?
|
|---|
| 41 | AND p.status = 'published'
|
|---|
| 42 | AND p.tags LIKE ?
|
|---|
| 43 | ORDER BY p.published_at DESC
|
|---|
| 44 | LIMIT 100
|
|---|
| 45 | `).all(site.id, `%"${tag}"%`);
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | renderPage(req, res, 'pages/tag', {
|
|---|
| 49 | pageTitle: `#${tag} — ${site.title}`,
|
|---|
| 50 | bodyClass: 'on-special',
|
|---|
| 51 | tag,
|
|---|
| 52 | posts,
|
|---|
| 53 | });
|
|---|
| 54 | });
|
|---|
| 55 |
|
|---|
| 56 | export default router;
|
|---|