07 — Multi-method
Many HTTP verbs on the same URL — register each verb with its own builder call on the same URL; they merge into one endpoint at .done().
Run this chapter in 30 seconds
- Open in StackBlitz → — full Node sandbox in your browser, no install.
- Wait for
npm installto finish, then in the Terminal tab run:npx tsx examples/07-multi-method/server.ts - Paste any request from the Try it section below into the Terminal (use
curl— the StackBlitz preview port is forwarded).
Concept
Call .get / .post / .delete (etc.) on the same URL — the builder collects them into a single endpoint with several verbs at .done(). Verbs you don't register respond 405 Method Not Allowed with an Allow header listing the supported ones. These verb calls can stand alone or sit alongside a .data store on the same URL to override specific verbs while default CRUD covers the rest.
Code
ts
import { mockr, mockGroup } from '@yoyo-org/mockr';
import { z } from 'zod';
interface CartItem { id: number; product_id: number; quantity: number }
type Endpoints = {
'/internal/cart': CartItem[];
'/api/cart': CartItem[];
};
const cart = mockGroup<Endpoints>()
.data('/internal/cart', [])
.get('/api/cart', (_req, ctx) => ctx.endpoint('/internal/cart').data)
.post('/api/cart', {
body: z.object({ product_id: z.number(), quantity: z.number() }),
fn: (req, ctx) => {
ctx.endpoint('/internal/cart').insert(req.body as CartItem);
return ctx.created(ctx.endpoint('/internal/cart').data);
},
})
.delete('/api/cart', (_req, ctx) => {
ctx.endpoint('/internal/cart').clear();
return ctx.noContent();
})
.done();
mockr({ port: 3007, groups: [cart] });Try it
Open in StackBlitz → — paste each curl into the StackBlitz Terminal once npx tsx examples/07-multi-method/server.ts is running.
bash
# read cart
curl -s http://localhost:3007/api/cart
# add line
curl -s -X POST http://localhost:3007/api/cart \
-H 'Content-Type: application/json' \
-d '{"product_id":1,"quantity":2}'
# clear
curl -s -X DELETE http://localhost:3007/api/cart -i
# unsupported verb — 405 + Allow header
curl -s -X PUT http://localhost:3007/api/cart -iWhat's next
Forward unmatched routes to a real backend → 08 — Proxy.