O

ouhammmourachid / blog-cms

Public

Headless blog backend: drafts, scheduled publishing, tags, cover images, automatic slugs and an RSS feed.

  • CMS
  • 0 deploys
  • 0 forks

Blog CMS with scheduled posts and RSS

Headless blog backend: drafts, scheduled publishing, tags, cover images, automatic slugs and an RSS feed.

What you get

  • Draft, scheduled and published states; a cron job publishes scheduled posts every 5 minutes
  • Slugs are generated from the title and kept unique
  • published_at is filled the moment a post goes live
  • Readers see only published posts; authors also see their own drafts
  • RSS 2.0 feed of the latest 20 posts at GET /rss.xml

Collections

tags

FieldTypeNotes
name (required)text
slug (required)text
ActionWho can do it
List / viewanyone
Createsigned-in users
Updatesigned-in users
Deletesigned-in users

posts

FieldTypeNotes
title (required)text
slugtextGenerated from the title if empty
excerpttextUsed in lists and RSS
bodyeditorRich text (HTML)
coverfileImages up to 10 MB
tagsrelation → tags (many)
status (required)selectdraft, scheduled or published
publish_atdateWhen a scheduled post goes live
published_atdateSet automatically
author (required)relation → usersSet by a hook to the signed-in user
ActionWho can do it
List / viewstatus = 'published' || author = @request.auth.id
Createsigned-in users
Updateauthor = @request.auth.id
Deleteauthor = @request.auth.id

Hooks

All hooks are in pb_hooks/main.pb.js and commented.

Setup

  • Any signed-in user can write posts. For a single-author blog, set the posts create rule to @request.auth.id = "YOUR_USER_ID", and do the same for tags.
  • Set the environment variable BLOG_SITE_URL: Your blog's public URL, used for links in the RSS feed (defaults to the Application URL)

Quick start

import PocketBase from "pocketbase"
const pb = new PocketBase("https://YOUR-INSTANCE.pocketshub.com")

// Published posts, newest first:
const posts = await pb.collection("posts").getList(1, 10, {
  filter: "status = 'published'", sort: "-published_at", expand: "tags",
})

// One post by slug:
const post = await pb.collection("posts").getFirstListItem(`slug = "${slug}"`)

// Schedule a post:
await pb.collection("posts").create({
  title: "Hello world", body: "<p>...</p>", status: "scheduled", publish_at: "2027-01-01 09:00:00Z",
})

Notes

  • Cover images come with a 1200x630 thumbnail, the size social cards use.

License

MIT

tags
  • id
  • name
  • slug
  • created
  • updated
posts
  • id
  • title
  • slug
  • excerpt
  • body
  • coversingle
  • tagsmultiple
  • statussingle
  • publish_at
  • published_at
  • authorsingle
  • created
  • updated

2 collections, 1 relation. Hover a collection to trace its relations

main.pb.js99 lines
/// <reference path="../pb_data/types.d.ts" />

// The signed-in user is always the author of the posts they create.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to write posts.")
    e.record.set("author", e.auth.id)
  }
  e.next()
}, "posts")

onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth() && e.record.original().getString("author") !== e.record.getString("author")) {
    throw new ForbiddenError("The author of a post can't be changed.")
  }
  e.next()
}, "posts")

// Runs on every create and update: fill the slug, and keep the publish dates consistent.
onRecordValidate((e) => {
  const post = e.record

  let slug = post.getString("slug").trim()
  if (!slug) slug = post.getString("title")
  slug = slug
    .toLowerCase()
    .normalize("NFKD")
    .replace(/[̀-ͯ]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 80)
  if (!slug) slug = "post"
  const taken = e.app.countRecords("posts", $dbx.exp("slug = {:slug} AND id != {:id}", { slug: slug, id: post.id }))
  if (taken > 0) slug = slug + "-" + $security.randomStringWithAlphabet(5, "abcdefghijklmnopqrstuvwxyz0123456789")
  post.set("slug", slug)

  const status = post.getString("status")
  if (status === "scheduled" && !post.getString("publish_at")) {
    throw new BadRequestError("Scheduled posts need a publish_at date.")
  }
  if (status === "published" && !post.getString("published_at")) {
    post.set("published_at", new DateTime())
  }
  if (status === "draft") {
    post.set("published_at", "")
  }

  e.next()
}, "posts")

// Every 5 minutes, publish scheduled posts whose time has come.
cronAdd("blog_publish_scheduled", "*/5 * * * *", () => {
  const due = $app.findRecordsByFilter(
    "posts",
    "status = 'scheduled' && publish_at != '' && publish_at <= @now",
    "publish_at",
    200,
    0,
  )
  for (const post of due) {
    post.set("status", "published")
    post.set("published_at", post.getString("publish_at"))
    $app.save(post)
  }
})

// GET /rss.xml  - the 20 latest published posts.
// Set BLOG_SITE_URL to your frontend (e.g. https://blog.example.com). Post links are <site>/<slug>.
routerAdd("GET", "/rss.xml", (e) => {
  const esc = (s) =>
    String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
  const meta = $app.settings().meta
  const site = ($os.getenv("BLOG_SITE_URL") || meta.appURL).replace(/\/+$/, "")

  const posts = $app.findRecordsByFilter("posts", "status = 'published'", "-published_at", 20, 0)
  const items = posts
    .map((p) => {
      const link = `${site}/${p.getString("slug")}`
      const date = new Date(p.getString("published_at").replace(" ", "T")).toUTCString()
      return (
        `<item><title>${esc(p.getString("title"))}</title>` +
        `<link>${esc(link)}</link><guid>${esc(link)}</guid>` +
        `<pubDate>${date}</pubDate>` +
        `<description>${esc(p.getString("excerpt"))}</description></item>`
      )
    })
    .join("")

  const xml =
    `<?xml version="1.0" encoding="UTF-8"?>` +
    `<rss version="2.0"><channel>` +
    `<title>${esc(meta.appName)}</title><link>${esc(site)}</link>` +
    `<description>${esc(meta.appName)} blog</description>` +
    items +
    `</channel></rss>`

  e.response.header().set("Content-Type", "application/rss+xml; charset=utf-8")
  return e.string(200, xml)
})