Skip to content

01 — Data list

.data(url, T[]) turns into a list endpoint with full CRUD. No glue code.

Run this chapter in 30 seconds

  1. Open in StackBlitz → — full Node sandbox in your browser, no install.
  2. Wait for npm install to finish, then in the Terminal tab run:
    npx tsx examples/01-data-list/server.ts
  3. Paste any request from the Try it section below into the Terminal (use curl — the StackBlitz preview port is forwarded).

Concept

Seed an array of items. mockr registers GET / POST / PUT / PATCH / DELETE on the URL. Mutations persist in memory across requests.

Code

ts
import { mockr, mockGroup } from '@yoyo-org/mockr';

interface Todo {
  id: number;
  title: string;
  done: boolean;
}

type Endpoints = {
  '/api/todos': Todo[];
};

const todos = mockGroup<Endpoints>()
  .data('/api/todos', [
    { id: 1, title: 'Buy milk', done: false },
    { id: 2, title: 'Write tests', done: true },
    { id: 3, title: 'Deploy to prod', done: false },
  ])
  .done();

mockr({ port: 3001, groups: [todos] });

Try it

Open in StackBlitz → — paste each curl into the StackBlitz Terminal once npx tsx examples/01-data-list/server.ts is running.

bash
# list
curl -s http://localhost:3001/api/todos

# insert (auto-generated id)
curl -s -X POST http://localhost:3001/api/todos \
  -H 'Content-Type: application/json' \
  -d '{"title":"New","done":false}'

# patch
curl -s -X PATCH http://localhost:3001/api/todos/1 \
  -H 'Content-Type: application/json' \
  -d '{"done":true}'

# delete
curl -s -X DELETE http://localhost:3001/api/todos/1 -i

POST returns the inserted item with a generated id. PATCH returns the merged item. DELETE returns 204.

What's next

Move data into a JSON file with hot-reload → 02 — Data files.

MIT License