Going further

Storage

Where documents live, and the rules Mortar applies whichever store you use.

Storage has two layers. A store keeps raw documents and is deliberately dumb. createContent wraps any store and applies every rule.

import { createContent } from '@mortar-kit/core';
import { createJsonFileStore } from '@mortar-kit/core/server';

const content = createContent({ store: createJsonFileStore({ dir: 'content' }), collections, bricks });

The rules

createContent returns a Content, with list, get, save, remove and move. Whatever the store, it:

  • normalizes on read, so pages always get documents of the right shape;
  • validates on save, and returns problems ({ ok: false, issues }) instead of throwing, so the admin can show them;
  • keeps slugs unique in each collection;
  • moves the document on a rename and keeps its id;
  • supports where, sort and limit when listing;
  • keeps orderable collections in their manual order: lists follow it, new documents go to the end, and move reorders (see Manual order);
  • refuses to delete a document while others reference it, and returns those documents;
  • runs writes through one createContent one at a time, so those checks still hold when the write lands.

Collection names are checked on every call, since a server function receives them from the browser.

The stores Mortar ships

Store Where Use
createJsonFileStore({ dir }) @mortar-kit/core/server One pretty-printed file per document, <dir>/<collection>/<slug>.json. Content can live in git. Writes are atomic.
createMemoryStore(seed?) @mortar-kit/core In memory: tests and demos.

The JSON-file store reads the whole folder to list a collection, which is fine for small sites.

Calling it from the browser

createContentServer({ content, auth }) (from @mortar-kit/core/server) turns a Content into the functions your app's 'use server' module exports. Reads are open to everyone, since your pages render from them. Every write (saving, deleting, reordering, uploads, asset details and folders) first calls auth.require with the request, because middleware can't tell the admin's server-function calls apart, and answers without revalidating, so a save never refetches into the open editor. Upload limits are set once: it raises the server-function body limit to fit createContent's maxAssetSize.

// src/server/mortar.ts (also imported by serverFunctions.serverSetup)
import { createContent } from '@mortar-kit/core';
import { createContentServer, createJsonFileStore } from '@mortar-kit/core/server';

import { auth } from './auth.ts';

export const content = createContent({ store: createJsonFileStore({ dir: 'content' }), blobs, collections, bricks });
export const server = createContentServer({ content, auth });
// src/server/content.ts
'use server';
import { server } from './mortar.ts';

export const list = server.list;
export const get = server.get;
export const save = server.save;
export const remove = server.remove;
export const move = server.move;
export const listAssets = server.listAssets;
export const uploadAsset = server.uploadAsset;
export const removeAsset = server.removeAsset;
export const updateAsset = server.updateAsset;
export const listAssetFolders = server.listAssetFolders;
export const saveAssetFolder = server.saveAssetFolder;
export const removeAssetFolder = server.removeAssetFolder;

Import src/server/mortar.ts from the module you give the plugin as serverFunctions.serverSetup, so the body limit is raised before the first upload arrives.

In the browser, contentClient(server, options) (from @mortar-kit/core) builds what the rest of the app needs from those functions: source, cached reads for routes, layouts and bricks; freshSource, uncached reads for the admin's preview; and content, the admin's reads and writes, which drops cached reads after every write that went through. Mortar depends on neither the router nor the server-function runtime, so pass their helpers:

// src/content.ts
import { contentClient } from '@mortar-kit/core';
import { query } from '@solidjs/router';
import { GET } from '@solidjs/web/server-functions';

import * as server from './server/content.ts';

export const { source, freshSource, content } = contentClient(server, { read: GET, cache: query, onWrite: () => query.clear() });

read: GET sends reads as GET requests (a POST counts as a mutation and would revalidate every query), and cache: query fetches a document once per request during server rendering and reuses it on hydration.

Several processes

Writes are serialized within one createContent. If several server processes share a store, the store itself needs to lock.

Want to keep content somewhere else? See Writing a store. Uploaded files have a store of their own: see Assets.

Starter content

seed(content, docs) saves starter documents into collections that are still empty, through createContent, so they're validated like an editor's saves. Collections that already have documents are left alone, so it's safe to call every time the server starts. It works with any store, a database as well as the JSON files.

await seed(content, {
  categories: [{ id: 'news', slug: 'news', fields: { name: 'News' } }],
  pages: [{ id: 'home', slug: 'home', fields: { title: 'Welcome' }, entries: [] }],
});

Collections are filled in the order given, so a reference can point at a document seeded before it. Leave out id and a random one is made. A document that doesn't validate throws, naming it and its problems. With the JSON-file store you can also just commit the files: they are the seed.

ContentStoreinterface

import { ContentStore } from '@mortar-kit/core'

interface ContentStore

Where documents live: raw data by collection name and slug. Implement it to keep content anywhere (files, a database, an API). Deliberately dumb; createContent applies every rule.

Properties

list: (collection: string) => Promise<unknown[]>

Every stored document of the collection, raw, each with slug set by the store (the key wins). [] if none.

get: (collection: string, slug: string) => Promise<unknown>

The raw document under slug (with slug set), or undefined. Throws if it exists but can't be read.

put: (collection: string, doc: Doc) => Promise<void>

Stores doc under doc.slug, replacing any document there.

remove: (collection: string, slug: string) => Promise<void>

Removes the document under slug; nothing happens if there is none.

createContentfunction

import { createContent } from '@mortar-kit/core'

function createContent(options: ContentOptions): Content & Pick<Required<Content>, "move" | "runAction"> & { assets?: Required<Assets> }

The rules around a store. Collection names are checked on every call (a server function receives them from the client): an unknown one throws. Throws at creation if a reference field names an unknown collection.

Parameters

Returns

Content & Pick<Required<Content>, "move" | "runAction"> & { assets?: Required<Assets> }

seedfunction

import { seed } from '@mortar-kit/core'

function seed(content: Content, docs: Readonly<Record<string, readonly SeedDoc[]>>): Promise<SeedResult>

Saves starter documents into every collection of docs that has none yet, in the order given (so references can point at documents saved earlier). Collections that already have documents are left alone, so it is safe to call on every start. Throws, naming the document and its problems, if one doesn't validate.

Parameters

content: Content
docs: Readonly<Record<string, readonly SeedDoc[]>>

Returns

Promise<SeedResult>

Example

await seed(content, {
  pages: [{ id: 'home', slug: 'home', fields: { title: 'Welcome' }, entries: [] }],
});

createJsonFileStorefunction

import { createJsonFileStore } from '@mortar-kit/core/server'

function createJsonFileStore(options: JsonFileStoreOptions): ContentStore

A content store backed by JSON files. Collection names and slugs are checked, so neither can escape dir. A file that can't be parsed is skipped when listing (and logged), so one bad file doesn't break every list on the site, but reading it directly throws.

Parameters

Returns

ContentStore

createContentServerfunction

import { createContentServer } from '@mortar-kit/core/server'

function createContentServer<User = unknown>(options: ContentServerOptions<User>): ContentServer

The server side of the app's content, for its "use server" module to export. It also raises the server-function request body limit to fit the content's largest upload, so import the module that calls it from the plugin's serverFunctions.serverSetup.

Parameters

options: ContentServerOptions<User>

Returns

ContentServer

Example

// src/server/mortar.ts (imported by serverFunctions.serverSetup too)
export const server = createContentServer({ content, auth });

// src/server/content.ts
'use server';
import { server } from './mortar.ts';
export const list = server.list;
export const get = server.get;
export const save = server.save;
// …and the same for remove, move, listAssets, uploadAsset, removeAsset,
// updateAsset, listAssetFolders, saveAssetFolder and removeAssetFolder

contentClientfunction

import { contentClient } from '@mortar-kit/core'

function contentClient(server: ContentServer, options?: ContentClientOptions): ContentClient

The app's content in the browser (and during SSR), over the functions of its "use server" module.

Parameters

Returns

ContentClient

Example

// src/content.ts
import { query } from '@solidjs/router';
import { GET } from '@solidjs/web/server-functions';
import * as server from './server/content.ts';

export const { source, freshSource, content } = contentClient(server, { read: GET, cache: query, onWrite: () => query.clear() });