Skip to content

Latest commit

 

History

History
217 lines (176 loc) · 9.24 KB

data-layer.md

File metadata and controls

217 lines (176 loc) · 9.24 KB
title Data Layer with TanStack DB
id data-layer
order 4
description Use TanStack DB as the data layer of a TanStack CMS app: CMS collections as live, writable TanStack DB collections, markdown files as collections, and live queries that join CMS content with other services.
keywords
tanstack cms
tanstack db
live queries
createCmsCollectionOptions
@tanstack/cms-client/db
@tanstack/cms-api/markdown
loadMarkdownDir
query collection
headless cms

TanStack CMS runs on two TanStack libraries:

  • TanStack Start is the application runtime. The admin, the public pages, and the API endpoints are Start routes mounted from a package, and every CMS operation is also a Start server function.
  • TanStack DB is the data layer for your app's own UI. Any CMS collection can be a live TanStack DB collection: components read it with live queries, write to it with optimistic mutations, and join it with data that lives outside the CMS.

The CMS owns the content model, validation, revisions, and the review queue. TanStack DB owns how app components read, combine, and update that content. Writes made through a TanStack DB collection go through the same CMS operations the admin uses, so none of the workflow is bypassed.

The built-in admin UI calls the server functions directly and doesn't use TanStack DB. TanStack DB is what you use in your own routes and components.

For diagrams of these paths, see Data Loading and Mutations in the architecture overview.

Three Sources, One Query Model

The repo has an example for each kind of source. Both read data with useLiveQuery from @tanstack/react-db; only the collection definitions differ.

Example Port Source Collections
db-sqlite 3021 The CMS store (embedded Postgres) One CMS collection, readable and writable from the page and from /content.
db-federated 3022 The CMS plus three services Product attributes, prices, and stock from mocked services, joined with localized copy from the CMS.

Run one with pnpm --filter db-sqlite dev.

CMS Collections in TanStack DB

createCmsCollectionOptions() from @tanstack/cms-client/db turns a CMS collection into TanStack DB collection options:

pnpm add @tanstack/cms-client @tanstack/db @tanstack/react-db @tanstack/query-db-collection @tanstack/query-core
// src/collections.ts
import { QueryClient } from '@tanstack/query-core'
import { createCollection } from '@tanstack/db'
import { createCmsClient } from '@tanstack/cms-client'
import { createCmsCollectionOptions } from '@tanstack/cms-client/db'

export const queryClient = new QueryClient()

// Same origin as the Start app that mounts the CMS API routes.
const cms = createCmsClient({ baseUrl: '' })

export interface ProductRow {
  name: string
  price: number
  stock: number
  published: boolean
}

export const productsCollection = createCollection(
  createCmsCollectionOptions<ProductRow>(cms, queryClient, 'product', {
    live: true, // subscribe to /api/cms/v1/events SSE stream to invalidate on server writes
    refetchInterval: 4000, // optional fallback polling
  }),
)

Passing live: true opens a browser EventSource against /api/cms/v1/events?collection=product (via subscribeCmsCollectionEvents(cms, queryClient, collection)) and invalidates the query whenever a document in that collection is published, unpublished, changed, or deleted. Collections backed by a read-only storage adapter (or configured with readOnly: true) automatically omit onInsert, onUpdate, and onDelete handlers unless overridden.

Components query it live and mutate it directly:

import { useLiveQuery } from '@tanstack/react-db'
import { productsCollection } from '../collections'

function Products() {
  const { data: products } = useLiveQuery({
    query: (q) => q.from({ p: productsCollection }).orderBy(({ p }) => p.name),
  })
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          {p.name}: {p.stock}{' '}
          <button
            onClick={() =>
              productsCollection.update(p.id, (d) => {
                d.stock = d.stock + 1
              })
            }
          >
            +
          </button>
        </li>
      ))}
    </ul>
  )
}

How reads and writes map to the CMS:

  • Reads page through list (with populate: false). Callers who can read the collection get drafts too, and anonymous callers get only published documents.
  • insert runs save with create: true, update runs save with publish: true, and delete runs deleteDoc. Updates publish immediately instead of saving a draft, so the live query shows the change.
  • Permissions still apply. A caller without publish rights gets their write staged in the review queue, and the live row keeps its old value until the change is approved. Validation errors and access failures reject the mutation, and TanStack DB rolls back the optimistic change.

The data-layer examples mount the CMS admin and API but not the public pages, and own / themselves:

// vite.config.ts (excerpt)
import { route } from '@tanstack/virtual-file-routes'
import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes'
import { definition } from './src/cms.definition'

tanstackStart({
  router: {
    virtualRouteConfig: createRoutes(definition, {
      public: false,
      custom: [route('/', './home.tsx')],
    }),
  },
})

Markdown Files as a Collection

Markdown content that lives in the repo is read into plain objects, not mounted as a storage adapter. loadMarkdownDir() from @tanstack/cms-api/markdown reads a directory of .md files with YAML frontmatter, which you expose from a Start server function and feed into a TanStack DB query collection:

// src/docs.functions.ts
import { join } from 'node:path'
import { createServerFn } from '@tanstack/react-start'
import { loadMarkdownDir } from '@tanstack/cms-api/markdown'

export const listMarkdownDocs = createServerFn({ method: 'GET' }).handler(async () => {
  const docs = await loadMarkdownDir(join(process.cwd(), 'content', 'posts'), {
    bodyField: 'body',
  })
  return docs
    .filter((doc) => doc.published !== false)
    .sort((a, b) => String(b.date).localeCompare(String(a.date)))
})
// src/collections.ts
import { QueryClient } from '@tanstack/query-core'
import { createCollection } from '@tanstack/db'
import { queryCollectionOptions } from '@tanstack/query-db-collection'
import { listMarkdownDocs } from './docs.functions'

export const queryClient = new QueryClient()

export const docsCollection = createCollection(
  queryCollectionOptions({
    queryKey: ['markdown-docs'],
    queryFn: () => listMarkdownDocs(),
    queryClient,
    getKey: (doc) => doc.id,
  }),
)

Name modules that export server functions *.functions.ts, not *.server.ts. TanStack Start refuses to build client code that imports a *.server.* file, even when that file only exports server functions.

Joining CMS Content with Other Services

Content rarely lives in one place. In db-federated, product attributes come from a PIM, prices and stock come from per-region services, and localized marketing copy is edited in the CMS. Each source is its own collection, and one live query joins them:

import { useLiveQuery } from '@tanstack/react-db'
import { and, eq } from '@tanstack/db'
import {
  copyCollection, // createCmsCollectionOptions(cms, queryClient, 'productCopy')
  inventoryCollection,
  pimCollection,
  pricesCollection,
} from '../collections'

function useCatalog(locale: string, region: string) {
  // `locale` and `region` are part of the query, so changing them re-runs it.
  return useLiveQuery({
    query: (q) =>
      q
        .from({ pim: pimCollection })
        .innerJoin({ price: pricesCollection }, ({ pim, price }) => eq(pim.id, price.productId))
        .innerJoin({ inv: inventoryCollection }, ({ pim, inv }) => eq(pim.id, inv.productId))
        .innerJoin({ copy: copyCollection }, ({ pim, copy }) => eq(pim.id, copy.productId))
        .where(({ price, inv, copy }) =>
          and(eq(price.region, region), eq(inv.region, region), eq(copy.locale, locale)),
        )
        .select(({ pim, price, inv, copy }) => ({
          id: pim.id,
          title: copy.title,
          price: price.amount,
          currency: price.currency,
          stock: inv.stock,
        })),
  })
}

An editor who changes a title in /content sees it in the catalog on the next refetch. The services, the CMS, and the components never know about each other; the query is the only place they meet.

Next Steps