O

ouhammmourachid / todo-api

Public

The classic todo backend, done properly: per-user lists and todos, due dates, priorities, completion timestamps and a stats endpoint.

  • Other
  • 0 deploys
  • 0 forks

Todo API (beginner friendly)

The classic todo backend, done properly: per-user lists and todos, due dates, priorities, completion timestamps and a stats endpoint.

What you get

  • Every user sees only their own lists and todos
  • Due dates and low/medium/high priority
  • completed_at is set and cleared automatically when done changes
  • GET /api/todos/stats returns total, done, open and overdue counts
  • Deleting a list deletes its todos

Collections

lists

FieldTypeNotes
title (required)text
colortextAny CSS color
owner (required)relation → usersSet by a hook to the signed-in user
ActionWho can do it
List / viewowner = @request.auth.id
Createsigned-in users
Updateowner = @request.auth.id
Deleteowner = @request.auth.id

todos

FieldTypeNotes
listrelation → listsOptional
title (required)text
notestext
donebool
due_datedate
priorityselectlow, medium, high
completed_atdateSet automatically
owner (required)relation → usersSet by a hook to the signed-in user
ActionWho can do it
List / viewowner = @request.auth.id
Createsigned-in users
Updateowner = @request.auth.id
Deleteowner = @request.auth.id

Hooks

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

Quick start

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

const list = await pb.collection("lists").create({ title: "Groceries" })
const todo = await pb.collection("todos").create({ list: list.id, title: "Milk", priority: "high" })
await pb.collection("todos").update(todo.id, { done: true })   // completed_at is set for you

const open = await pb.collection("todos").getFullList({ filter: "done = false", sort: "due_date" })
const stats = await pb.send("/api/todos/stats", {})           // { total, done, open, overdue }

Notes

  • A good first pocket for learning PocketBase API rules and hooks: every file is short and commented.

License

MIT

lists
  • id
  • title
  • color
  • ownersingle
  • created
  • updated
todos
  • id
  • listsingle
  • title
  • notes
  • done
  • due_date
  • prioritysingle
  • completed_at
  • ownersingle
  • created
  • updated

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

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

// Lists belong to the signed-in user who creates them.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to create lists.")
    e.record.set("owner", e.auth.id)
  }
  e.next()
}, "lists")

// Todos belong to the signed-in user, and only go into their own lists.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to create todos.")
    e.record.set("owner", e.auth.id)
    const listId = e.record.getString("list")
    if (listId) {
      let list
      try {
        list = e.app.findRecordById("lists", listId)
      } catch (_) {
        throw new BadRequestError("List not found.")
      }
      if (list.getString("owner") !== e.auth.id) throw new ForbiddenError("That list isn't yours.")
    }
  }
  e.next()
}, "todos")

// The owner of lists and todos never changes.
onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth() && e.record.original().getString("owner") !== e.record.getString("owner")) {
    throw new ForbiddenError("The owner can't be changed.")
  }
  e.next()
}, "lists", "todos")

// Moving a todo to another list: that list must be yours too.
onRecordUpdateRequest((e) => {
  const listId = e.record.getString("list")
  if (!e.hasSuperuserAuth() && listId && listId !== e.record.original().getString("list")) {
    let list
    try {
      list = e.app.findRecordById("lists", listId)
    } catch (_) {
      throw new BadRequestError("List not found.")
    }
    if (list.getString("owner") !== e.auth.id) throw new ForbiddenError("That list isn't yours.")
  }
  e.next()
}, "todos")

// Keep completed_at in step with done, on every create and update.
onRecordValidate((e) => {
  if (e.record.getBool("done")) {
    if (!e.record.getString("completed_at")) e.record.set("completed_at", new DateTime())
  } else {
    e.record.set("completed_at", "")
  }
  e.next()
}, "todos")

// GET /api/todos/stats  -> { total, done, open, overdue } for the signed-in user.
routerAdd(
  "GET",
  "/api/todos/stats",
  (e) => {
    const owner = e.auth.id
    const now = new DateTime().string()
    const total = $app.countRecords("todos", $dbx.hashExp({ owner: owner }))
    const done = $app.countRecords("todos", $dbx.hashExp({ owner: owner, done: true }))
    const overdue = $app.countRecords(
      "todos",
      $dbx.exp("owner = {:owner} AND done = FALSE AND due_date != '' AND due_date < {:now}", { owner: owner, now: now }),
    )
    return e.json(200, { total: total, done: done, open: total - done, overdue: overdue })
  },
  $apis.requireAuth(),
)