Skip to Content
onedef

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.

lib/backend.ts
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

inputthe validated input. Handlers only ever see parsed values.
idthe member id, for operations on one object (get, delete, actions)
objectthe current object, loaded through get, when the action says needs: 'object'
ctxwhat context() returned for this request
clienta typed client bound to this same request, to call other operations without HTTP
requestthe 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:

codeHTTPcodeHTTP
BAD_REQUEST, INVALID_INPUT400RATE_LIMITED429
UNAUTHORIZED401INTERNAL500
FORBIDDEN403NOT_IMPLEMENTED501
NOT_FOUND404UPSTREAM_ERROR502
CONFLICT409UNAVAILABLE503

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:

If you'd rather not write persistence for simple objects, implementStore writes list, get and delete for you. See Storage.

On this page