The backend
implement() attaches one handler per operation. Input is validated before it runs, output after.
implement(contract, handlers) is your backend. Only the server imports it.
import { fail, implement } from 'onedef'
import { contract } from './contract'
export const backend = implement(contract, {
// runs once per request; whatever it returns is `ctx` in every handler
context: async ({ request }) => ({ userId: await verifyUser(request) }),
songs: {
list: () => db.songs.list(),
get: async ({ id }) => (await db.songs.get(id)) ?? fail('NOT_FOUND', `No lesson "${id}"`),
create: ({ input, ctx }) => db.songs.create(input, ctx.userId),
delete: ({ id }) => db.songs.delete(id),
rename: ({ object, input }) => db.songs.save({ ...object, title: input.title }),
},
})TypeScript checks every handler against the contract. A missing handler, a misspelled operation or a wrong return type is a compile error.
What a handler receives
input | the validated input. Handlers only ever see parsed values. |
id | the member id, for operations on one object (get, delete, actions) |
object | the current object, loaded through get, when the action says needs: 'object' |
ctx | what context() returned for this request |
client | a typed client bound to this same request, to call other operations without HTTP |
request | the incoming Request, when there is one |
Outputs are validated too, and fields the contract doesn't declare are stripped. So REST, RPC, MCP and in-process calls all return exactly the same shape, and nothing extra leaks.
Errors
fail(code, message) throws an error every surface understands:
| code | HTTP | code | HTTP | |
|---|---|---|---|---|
BAD_REQUEST, INVALID_INPUT | 400 | RATE_LIMITED | 429 | |
UNAUTHORIZED | 401 | INTERNAL | 500 | |
FORBIDDEN | 403 | NOT_IMPLEMENTED | 501 | |
NOT_FOUND | 404 | UPSTREAM_ERROR | 502 | |
CONFLICT | 409 | UNAVAILABLE | 503 |
REST answers with the status, the typed client throws an ApiError with the same code,
the CLI prints it and exits non-zero, and MCP returns a tool error the agent can read.
fail('NOT_FOUND', '…', { data }) passes structured details along.
Calling the backend in process
local(backend) is a transport that calls handlers directly: no HTTP, no serialization.
Use it in server components, jobs and tests.
import { createClient, local } from 'onedef'
const api = createClient(contract, local(backend))
await api.songs.get({ slug: 'la-vie-en-rose' })Serving it
The backend plugs into the surfaces as plain fetch handlers:
- REST, RPC and OpenAPI:
toNextHandlers(backend)ortoFetchHandler(backend) - MCP:
createMcpHandler(backend)
If you'd rather not write persistence for simple objects, implementStore writes list,
get and delete for you. See Storage.