Types and JSON Schema
Derive application types, validate operation inputs, and export JSON Schema from your models
Your model definitions already contain the information needed for application types and input validation. You do not need a database connection or a generated client to use these helpers.
A nested DB type
InferDatabase maps your schema’s model names to commonly used types:
import type { InferDatabase } from "viborm/client";
import type * as schema from "./schema";
export type DB = InferDatabase<typeof schema>;
type Post = DB["post"]["Row"];
type NewPost = DB["post"]["Create"];
type PostUpdate = DB["post"]["Update"];
type PostFilter = DB["post"]["Where"];
type FindPosts = DB["post"]["FindMany"];
InferDatabase is exported by viborm/client in V1.
Row is the default scalar result, not a row with every relation loaded.
Schema-level .omit() is respected. Client extensions and defaultOmit() are
not part of this schema-only view. Create and Update describe input data;
FindMany describes the complete operation arguments.
Keep the original inferred schema type. Annotating your schema as the broad
Schema type loses its specific model and field information.
Dot-style namespaces
DB["post"]["Create"] is derived automatically. If you prefer
DB.Post.Create, declare aliases explicitly:
type Database = InferDatabase<typeof schema>;
export namespace DB {
export namespace Post {
export type Row = Database["post"]["Row"];
export type Create = Database["post"]["Create"];
}
}
These are TypeScript types, not SQL database namespaces. For PostgreSQL schemas or MySQL database qualification, see Database namespaces.
Types for a specific operation
Use OperationPayload for arguments and OperationResult for a concrete
projection. A findMany result is an array; index it with [number] for one row.
import type { OperationPayload, OperationResult } from "viborm/client";
import type * as schema from "./schema";
type FindPosts = OperationPayload<"findMany", typeof schema.post>;
type PostTitle = OperationResult<
"findMany",
typeof schema.post,
{ select: { title: true } }
>[number];
// { title: string }
OperationPayload retains optional operation arguments: use NonNullable when
indexing a payload or one of its optional clauses. It does not package the
client’s generic exactness guards into a universal forwarding helper. A concrete
query function keeps its inferred arguments and result without widening the schema.
For results affected by a concrete client’s extensions or defaults, infer from
an application query function with Awaited<ReturnType<typeof loadPosts>>.
Validation schemas and their types
getSchemas exposes the validation schemas for the complete model graph.
core.create describes create data; args.create describes the complete call,
including its data property and projection options.
import { getSchemas } from "viborm";
import type { InferInput, InferOutput } from "viborm/validation";
import * as schema from "./schema";
const schemas = getSchemas(schema);
const createPost = schemas.post.core.create;
type CreatePostInput = InferInput<typeof createPost>;
type ValidatedCreatePost = InferOutput<typeof createPost>;
const validation = createPost["~standard"].validate({
title: "Hello",
});
// Inspect validation.issues or validation.value; required fields depend on your model.
InferOutput means the normalized output of validation, not a record read
from the database. Use OperationResult for query results.
These helpers return VibORM validation schemas implementing Standard Schema.
They do not generate Zod or Valibot objects, a database row validator, or those
libraries’ pick and extend APIs. A scalar’s .schema() can consume a
Standard Schema validator; that is distinct from generating one from a model.
A BigInt field takes a JavaScript bigint or an integer string ("-42",
validated to -42n), which is how a bigint crosses a JSON boundary. A JSON
number is refused: past 2^53 it may already have lost integer precision. The
typed client still asks for a bigint; the string form is for payloads that
arrive as JSON, through UntypedClient or validateOperationPayload.
Every issue at once
A validation schema stops at the first issue. To report every issue of a
payload in one call — each field, each list item, every unknown or missing
key — pass allIssues to parse:
import { parse } from "viborm/validation";
const result = parse(createPost, payload, { allIssues: true });
// result.issues: one entry per problem, each with its own path
parse is the only entry point to this mode: client operations and
validateOperationPayload still report the first issue.
A refusal inside a union (a filter’s shorthand or operator object, a single
item or a list) names the member the value was written for and that member’s
path, such as where.age.gt. When no member reads further into the value than
the others, the message lists what each member expected.
To validate a full payload selected by model and operation:
import { getOperationPayloadSchema, validateOperationPayload } from "viborm";
const findPostsSchema = getOperationPayloadSchema(schema, "post", "findMany");
const payload = validateOperationPayload(schema, "post", "findMany", {
where: { title: { contains: "Hello" } },
});
validateOperationPayload returns the normalized payload or throws. This checks
the schema language, not authorization or whether a driver can execute the work.
The thrown ValidationError, like one a client operation raises, names its model
in meta.model and in its message (Validation failed for post.findMany: …).
Export JSON Schema
Use toJsonSchema to describe accepted input:
import { toJsonSchema } from "viborm/validation";
const createPostJson = toJsonSchema(createPost, "draft-2020-12");
Supported targets are draft-07 (the default), draft-2020-12, and
openapi-3.0. Recursive schemas use $ref references. Conversion throws only
for an unsupported target or a schema node with no JSON form at all, such as a
custom schema type outside VibORM’s own.
The document accepts what the validator accepts for every value JSON can carry:
- a BigInt is a string with an integer
pattern; - a decimal is a string whose
patterncarries the field’s declared precision and scale ("1.555"is refused for scale 2,"1.500"is not); - an identifier format (
uuid,uuidv7,ulid,ksuid,nanoid,cuid, with its prefix) is a stringpattern, not aformat.
What lives in code rather than in shape is not in the document: a .schema()
refinement, a whole-object rule such as “name at least one of these keys”, or
polygon geometry. Validate with VibORM where those matter.
The Standard JSON Schema interface lets you choose a direction explicitly:
const inputJson = createPost["~standard"].jsonSchema.input({
target: "draft-2020-12",
});
const outputJson = createPost["~standard"].jsonSchema.output({
target: "draft-2020-12",
});
Again, output describes validation output, not database query results.
JSON Schema describes data shapes; it does not replace VibORM’s runtime
validation, database constraints, or application authorization.
This is separate from parseSchema and serializeSchema in
viborm/schema/json, which read and write VibORM model-definition documents.
Render TypeScript descriptions
For tools that need TypeScript source text rather than compiler-inferred types:
import { renderOperationResultType, renderSchemaType } from "viborm";
const modelsText = renderSchemaType(schema);
const resultText = renderOperationResultType(schema, "post", "findMany", {
select: { title: true },
});
These functions return strings, not live TypeScript types or JSON Schema.
renderSchemaType renders a recursive VibORMSchema declaration. Runtime
rendering cannot recover a custom JSON validator’s erased TypeScript generic,
so that value is rendered as unknown. Client extensions and client-level
defaults are not included.
Import reference
| Import path | Helpers |
|---|---|
viborm |
getSchemas, getOperationPayloadSchema, validateOperationPayload, renderSchemaType, renderOperationResultType |
viborm/client |
InferDatabase, OperationPayload, OperationResult, OperationPayloadSchema, ValidatedOperationPayload |
viborm/validation |
InferInput, InferOutput, ModelCoreInput, ModelOperationInput, parse, toJsonSchema, createJsonSchemaConverter, JsonSchema |
See Standard Schema V1 for the validation interface and model-schema reference.