HTTP (any framework)
uql-orm/http serves your entities to a client: one API takes a client’s call, checks what it may reach, holds it to the signed-in user’s policies and runs it in a transaction where it writes. HTTP is the transport uql ships, and any other (a tRPC or oRPC procedure, a server action) calls the same API. The client sends the same query you write on the server: one query, every transport.
The API
Section titled “The API”import { createApi, toFetchHandler } from 'uql-orm/http';import { Post, User } from './shared/models/index.js';import { pool } from './uql.config.js';
const api = createApi({ pool, include: [User, Post] });const handler = toFetchHandler(api);createApi takes the options every transport shares; a transport only carries calls to api.call(call, context), which takes a call as JSON and answers as JSON.
include is required and lists the only entities a call can reach. A $populate, filter, sort or write that leads through a relation to an entity outside it is a 403, so an entity holding secrets stays unreachable unless you list it. Relations a middleware adds are allowed.
Transports
Section titled “Transports”toFetchHandler(api) returns a web-standard (request: Request) => Promise<Response>. Mount it on a catch-all under the API’s base, /api/v1 here so a later version can sit beside it: it reads the last two segments of the path as the entity and the op. Express takes toExpress(api) instead, and any other framework toRequestHandler(api), which takes a plain request object and answers { status, body, headers? }, or undefined for a route the API does not serve (see Fastify). A procedure calls the API itself (tRPC, oRPC).
| Runtime | Mount |
|---|---|
| Hono, Elysia | app. |
Bun. |
{ routes: { '/ |
| Cloudflare Workers | export default { fetch: handler } |
| Next.js, Astro, React Router, TanStack Start | a catch-all route under / |
| Nitro / h3 | from; on h3 v2, (event) => handler |
What a client may do
Section titled “What a client may do”Nothing is exposed by default: defining an entity serves nothing, and a client reaches only the entities an API’s include names, through a relation too. What a client may do to one is its definition’s wire, every operation where unset:
import { defineEntity, f } from 'uql-orm';
export const User = defineEntity({ name: 'User', wire: ['read', 'insert', 'update'], fields: { id: f.number().autoIncrement(), name: f.string(), email: f.string().wire(['read']), password: f.string().wire(['insert']), },});
const api = createApi({ pool, include: [Post, User] });- An entity’s
wireis what it takes:'read','insert','update','delete'. A save needsinsertandupdate, and so does a relation a write nests, which the cascade saves; an update nesting a to-many also deletes the rows it no longer lists, so it needsdeleteon the target.wire: falsekeeps an entity off every API, andcreateApirefuses one ininclude. A subclass declaring none takes its base’s. - A field’s
wireis on its builder, a relation’s in its options:'read','insert'or'update', orfalsefor nothing. A decorated class says the same,@Entity({ wire }),@Field(f.string().wire(false)),@OneToMany(() => Session, { mappedBy, wire: false }). - It holds wherever the entity is reached: hide
addressonEmployeeand/company/findManypopulatingemployeesleaves it out too. readis every way of reading a value:$select,$where,$sort,$count, a populated relation. Filtering by a hiddenpasswordwould read it a character at a time, so it is refused like selecting it, and so is a JSON path into a hidden column ('meta.plan')..eager(false)is not a guard: it leaves a field out of a read naming no fields, and a client’s$select: { password: true }still reads it. Hide a secret from clients with.wire(false).- A write the querier would drop, to a computed field or an update of an
updatable(false)one, is refused rather than ignored. - A call naming what it may not reach is a
403naming the path ('creator.password' cannot be read through this API), and a read naming no$selectleaves out what it may not read, at every depth it populates.
Every API serving an entity shows the same members. To narrow one API further, refuse in its middleware (below). Serving an ORM over HTTP without leaking a column tells why the rule lives on the field.
The pool
Section titled “The pool”The API runs on the pool you pass. Usually one module builds it and is also what uql-migrate reads:
import type { Config } from 'uql-orm';import { PgQuerierPool } from 'uql-orm/postgres';import { Post, User } from './shared/models/index.js';
export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL,});
export default { pool, entities: [User, Post] } satisfies Config;For a database per tenant, pass a function instead. It gets the transport’s context and the context contextOf resolved, and runs only after every middleware passes:
const api = createApi<Request>({ include: [User, Post], pool: (request) => poolFor(tenantOf(request)),});Wire protocol
Section titled “Wire protocol”Every call is {base}/{entity}/{op}: the entity at its kebab-cased class name, so UserProfile lives at /user-profile, and the op a querier method’s name: findMany, findManyAndCount, findManyPage, findOne, findOneById, count, insertOne, insertMany, saveOne, saveMany, updateMany, updateOneById, deleteMany, deleteOneById. The rest of the call is one JSON object of named keys:
| Key | Holds | Taken by |
|---|---|---|
id |
the key of the row, whichever field carries . |
find, update, delete |
query |
the query | every op but insert* and save* |
payload |
a row, an array of rows, or an update’s changes | the writes |
hard |
true to delete a soft-deleting entity’s rows for good |
delete, delete |
A read is a GET with that object URL-encoded in ?q= (left out when empty), or a QUERY or POST with it as the body. A write is a POST with it as the body:
GET /api/v1/user/findMany?q={"query":{"$where":{"status":"active"},"$limit":20}}GET /api/v1/user/findOneById?q={"id":42}POST /api/v1/user/insertOne {"payload":{"email":"ann@example.com"}}POST /api/v1/user/updateOneById {"id":42,"payload":{"name":"Ann"}}POST /api/v1/user/deleteMany {"query":{"$where":{"status":"banned"}},"hardDelete":true}q is shown unencoded. With curl:
curl -G https://example.com/api/v1/user/findMany \ --data-urlencode 'q={"query":{"$where":{"status":"active"},"$limit":20}}'
curl https://example.com/api/v1/user/insertOne \ -H 'content-type: application/json' \ -d '{"payload":{"email":"ann@example.com"}}'A read also takes HEAD, answered as its GET without the body. What changes the result lives in the call; headers carry only what concerns the request: Authorization, keys, tracing. A body needs content-type: application/json, which a plain HTML form cannot send, so no cross-site form can write; any other is a 415. A method the op does not take is a 405 with an Allow header, and an entity or op the API does not serve a 404, both of kind: 'usage'. A key the op does not take is a 400: an id on an op not by id, a payload on a read, a query on an insert or a save, a hardDelete on anything but a delete. Values are JSON-typed and never coerced, so "$limit": "10" is refused. Give a page a $limit.
JSON holds no Date or bigint, so a bigint travels as its digits and a Date as its ISO text. The API reads a call’s filters and rows back by the entity, and the client reads results the same way, so a date stays a date and a wide integer exact on every engine.
Each write runs in a transaction. Updates and deletes answer how many rows they changed. A delete soft-deletes where the entity can, unless the call says hardDelete: true, and a delete that names no rows is refused. $lock is refused too, since each call commits on its own.
A success is a 200 with the result under data: what the pool’s method answers (findManyAndCount answers [rows, count]), which the client unwraps. A failure answers its HTTP status, its error kind when it has one, and the path in the call that is at fault, so a form can point at the field:
{ "data": ... }{ "error": { "message": "'password' cannot be read through this API", "status": 403, "kind": "security", "path": ["query", "$where", "password"] } }A malformed call is a 400, and so is a $ key the query does not take, such as a misspelt clause or $lock, rather than being dropped and answering another read. So is a write optimistic locking refuses. A policy or what a client may do refusing is a 403, and a stale version a 409. A duplicate or a missing referenced row answers 409 Conflict, a not-null or check violation 400 Bad Request, and a deadlock or serialization failure 503 Service Unavailable, never with the driver’s message, which would leak table names and values. Only a UQL error answers its own status and message, a UqlRequestError a middleware throws included; any other error, whatever status it carries, is a 500 Internal Server Error.
encodeCall(call, readMethod) and decodeRequest(request) from uql-orm/http are the two halves of this protocol, for a client or a server of your own; a client in another language follows the rules above.
HTTP QUERY (RFC 10008)
Section titled “HTTP QUERY (RFC 10008)”QUERY carries a read’s call in the body like POST, so a large $where never hits a URL-length limit, while saying the request is safe and repeatable as a GET does.
The handler accepts it, but your framework must route it. Hono and Elysia .mount(), Bun.serve, Express’s toExpress, fastify.all from Fastify 5.11, a TanStack Start ANY handler, and an Astro ALL export or src/fetch.ts all do. Next.js route handlers and React Router resource routes take the standard verbs only; send their reads as POST when a URL grows too long. The client sends GET unless you choose another.
Middleware
Section titled “Middleware”A middleware runs around each call, before the database is touched, and can be async. It receives the call (entity, op, id, the decoded query, the payload, hardDelete), the transport’s context (the framework’s request), and next. Reshape the call before next, reshape what next resolves to, or throw to abort: a UqlRequestError answers its 4xx status and message, and any error UQL did not raise a generic 500.
import { UqlRequestError } from 'uql-orm';import { type ApiMiddleware, createApi } from 'uql-orm/http';
const authenticated: ApiMiddleware<Request> = async (call, request, next) => { if (!(await authenticate(request))) { throw new UqlRequestError('unauthorized', 401); } return next(call);};
const api = createApi({ pool, include: [User], use: [authenticated] });An entity’s own middleware goes in its serve, typed by the entity, so it reads and writes its members; narrowing on call.op types the payload. It runs on that entity’s calls alone, after the API’s:
import { type EntityMiddleware, serve } from 'uql-orm/http';
const stamped: EntityMiddleware<Post, Request> = (call, request, next) => call.op === 'insertOne' ? next({ ...call, payload: { ...call.payload, authorId: userOf(request) } }) : next(call);
const api = createApi({ pool, include: [serve(Post, { use: [stamped] })], use: [authenticated],});Middleware runs in order, first to last, after the call is checked against what a client may do: what a middleware adds is the server’s own. It sees results as the entity holds them, a Date as a Date. Hide a field with .wire(false) rather than stripping it from results: a middleware stripping rows still lets a client filter by the field.
Tenant scoping
Section titled “Tenant scoping”Don’t scope tenants by adding to $where in a middleware: that misses joined relations and checks no write. Pass contextOf and declare policies instead. The whole call then runs inside withContext, so every query in it is scoped and the client cannot opt out:
import { UqlRequestError } from 'uql-orm';
const api = createApi<Request>({ pool, include: [Invoice], contextOf: async (request) => { const session = await authenticate(request); // a verified session or JWT if (!session) throw new UqlRequestError('unauthorized', 401); return { tenantId: session.tenantId }; },});Policies guard writes as well: an insertOne for another tenant is a 403, and a saveOne onto another tenant’s row a 409. See Multi-tenancy for the policies themselves.
Custom routes beside it
Section titled “Custom routes beside it”The API serves single-entity calls. Other paths are a 404 from toFetchHandler and fall through to next() in Express, so your own routes can share the prefix. Write those for multi-entity transactions, aggregations, raw SQL, uploads and streaming.