Migrating an extension
Move an extension written for the earlier contract to parts, member by member
The extension contract is now one function, extension(name, ...parts), and
the functions that build a part: the six primitives call, unit, args,
rule, defaults and methods, with around (a call with a second
moment), fields and disclosure. Inside the parts, imported words carry the
rest (target, watch, settled, arg, only, check, text, …). Each
part and each word brings into your bundle only the code that runs it. This
page maps each member of the earlier definition object to its part, then
lists what goes without replacement and what changes for users of the
official extensions.
The rules an extension follows are in Create an extension. Error texts changed too: match errors on their class and code, not on their message.
In the pairs below, the “before” block is the earlier contract, which no longer compiles, and the “after” block is the extension to write now.
One spelling
defineExtension, defineHooks, enableExtensions and an object literal
passed to $extends() are gone. So is a function of the client
passed to $extends(). An extension is a value, applied with
client.$extends(value):
// Before
const timing = defineExtension({
name: "timing",
async query({ proceed }) {
return proceed();
},
});
// After
import { around, extension } from "viborm";
const timing = extension(
"timing",
around(() => async (run) => run())
);
client.$extends(timing);
An extension that names models was bound with
defineExtension<typeof schema>()({...}). Write it inside $extends(...) to
type it from the client, or bind it with parts<typeof schema>() when it is
written apart, or write it with plain extension(...) and let $extends()
check its names when it is applied (see
Extensions written apart):
// Before
const postTools = defineExtension<typeof schema>()({ name: "post-tools", /* … */ });
// After
import { parts } from "viborm";
import type { schema } from "./schema";
const postTools = parts<typeof schema>().extension("post-tools" /* , parts… */);
A factory passed to $extends(), client.$extends((base) => …), has no
replacement form: build the extension as a value. One that read the schema to
build its rows passes a function of the schema to rule:
rule((schema) => entries).
Member by member
| Earlier member | Part |
|---|---|
request |
call((c) => { c.set(patch) }, target?) |
query |
around((c) => async (run) => …, target?) |
onWriteOutcome |
settled(c, fn) in the first moment, on target(writes) |
written |
watch(c, …) and settled(c, …) in a call on target(writes) |
retry |
again(run) in an around |
route |
via(run, driver) in an around |
transaction |
unit on "transaction", with run(u, sql) |
statement |
unit on "statement", { rewrites: true }, with next(sql) |
observe, observes |
unit((u, next) => …) with the words text, parameters, driver, failure |
controls |
args({...}) with its modifiers |
rows.control, rows.default, rows.models |
An argument oneOf(...modes).default(d), and root / related written with when |
rows.verbs |
The keys of rule; named predicates become shared constants |
rows.confine |
confine: within(where) in the model’s rule entry |
deletion |
rule({ m: { delete: { instead: keep(…) } } }) |
data |
defaults({ m: { create, update } }) |
order |
defaults({ m: { orderBy } }) |
result |
fields({...}) |
client, model |
methods((scope) => ({ $name })), modelMethods((scope) => ({ model: { … } })) |
diagnostics of an error |
disclosure({ sql, parameters, … }) |
{ control, path }, { now: true }, { $row, up }, { $exists }, { $if } |
arg(name, path), now, row(column, up), exists(…), provided(…) |
request → call
input is c.args, controls is c.values. The patch is passed to
c.set instead of being returned. A map of models and operations becomes one
part per entry, selected with target:
// Before
request: {
post: {
findMany({ input }) {
return { take: Math.min(input.take ?? 100, 100) };
},
},
},
// After
import { call, extension, target } from "viborm";
const db = client.$extends(
extension(
"bounded-reads",
call((c) => {
c.set({ take: Math.min(c.args.take ?? 100, 100) });
}, target("post", "findMany"))
)
);
A generic request function ran for model operations only: select them with
target(models). A call without a target sees raw queries too
(c.kind === "raw"), whose arguments it cannot patch. c.args shows every
argument of the call, read-only; a handler that read input relied on the
result-shaping keys being absent from it.
query → around
proceed is run, input is run.input, mode is run.mode; kind,
model and operation stay on c. around is imported on its own: it is
not call.around.
// Before
query: {
post: {
async findMany({ mode, input, proceed }) {
beforeRead({ mode, input });
return proceed();
},
},
},
// After
import { around, extension, target } from "viborm";
const db = client.$extends(
extension(
"around-posts",
around((c) => async (run) => {
beforeRead({ mode: run.mode, input: run.input });
return run();
}, target("post", "findMany"))
)
);
onWriteOutcome → settled
// Before
async update({ onWriteOutcome, proceed }) {
onWriteOutcome(({ certainty }) => enqueueRefresh({ certainty }));
return proceed();
},
// After
import { call, extension, settled, target, writes } from "viborm";
const refresh = extension(
"refresh",
call((c) => {
if (c.model === "post" && c.operation === "update")
settled(c, ({ certainty }) => enqueueRefresh({ certainty }));
}, target(writes))
);
settled needs a target that is a set of writes (target(writes),
target(deletes), target("post", writes)): a target that names one
operation (target("post", "update")) brings nothing that watches writes,
and settled there is refused with a TypeError. A failure in settled
rejects the call: a VibORM error as it is, anything else as a QueryError.
The functions of several extensions all run, in chain order, and the first
failure rejects the call. settled is also told of a write that may have
committed (certainty: "may-have-committed").
written → watch and settled
// Before
written: () => ({
wants: (model) => model === "order",
rows: (model, kind, rows) => keep(rows),
settled: ({ certainty }) => publish(certainty),
}),
// After
import { call, extension, settled, target, watch, writes } from "viborm";
const outbox = extension(
"outbox",
call((c) => {
watch(c, {
wants: (model) => model === "order",
rows: (model, kind, rows) => keepRows(rows),
});
settled(c, ({ certainty }) => publish(certainty));
}, target(writes))
);
retry → again
retry was asked after a failure. again(run) says whether run() may be
called again, and you call it:
// Before
retry: (error, attempt) => attempt < 3 && isRetryableError(error),
// After
import { again, around, extension } from "viborm";
const resilience = extension(
"resilience",
around(() => async (run) => {
for (let attempt = 1; ; attempt++) {
try {
return await run();
} catch (error) {
if (attempt >= 3 || !again(run) || !isRetryableError(error)) throw error;
}
}
})
);
route → via
// Before
route: ({ operation }) => (operation.startsWith("find") ? replica : undefined),
// After
import { around, extension, reads, target, via } from "viborm";
const replicas = extension(
"replicas",
around(() => (run) => via(run, replica), target(reads))
);
transaction → unit and run
// Before
transaction: async (run) => {
await run(sql`SET LOCAL app.tenant = ${tenant}`);
},
// After
import { extension, run, sql, unit } from "viborm";
const tenantSession = extension(
"tenant-session",
unit(async (u, next) => {
await run(u, sql`SET LOCAL app.tenant = ${tenant}`);
return next();
}, ["transaction"])
);
statement → a rewriting unit
// Before
statement({ statement, model }) {
return model === "post" ? sql`${raw("/* posts */ ")}${statement}` : statement;
},
// After
import { extension, raw, sql, statement, unit } from "viborm";
const labels = extension(
"statement-labels",
unit(
(u, next) =>
u.model === "post" ? next(sql`${raw("/* posts */ ")}${statement(u)}`) : next(),
["statement"],
{ rewrites: true }
)
);
observe and observes → unit and its words
observes declared which facts core produced; now a word reads a fact when
you need it, and a fact no word reads is not produced. The rendered text is
read by text(u) (not sql(u): sql is the tagged template):
// Before
observes: { observesLifecycle: true, wants: (need) => need === "statement" },
observe(unit, proceed, facts) {
const known = facts?.read();
void proceed().then((completion) => record(unit, known, completion));
},
// After
import { extension, failure, text, unit } from "viborm";
const observer = extension(
"observer",
unit(async (u, next) => {
const sent = u.kind === "statement" ? text(u) : undefined;
const end = await next();
record(u, sent, end, failure(u));
return end;
})
);
A unit handler is awaited and runs in the call: what it throws fails the call.
Contain your own failures. next() is called exactly once; there is one
statement unit per physical send (a native batch is one, its members read
by statements(u)). An extension emits units of its own kind with work,
and attaches facts with note.
controls → args
| Earlier | Now |
|---|---|
{ oneOf: ["a", "b"] } |
oneOf("a", "b") |
{ schema: v.string() } |
accepts(v.string()) (a bare schema is refused) |
on: "reads", "writes", a list |
.on(reads), .on(writes), .on([...]); nothing for every operation |
required: true |
.required() everywhere it is accepted, or .required([...models]) |
bound: true |
bound(schema) |
uncacheable: true |
.volatile() |
// Before
controls: { tenant: { schema: v.string(), required: true } },
// After
import { accepts, args, extension } from "viborm";
import { v } from "viborm/validation";
const tenancy = extension(
"tenancy",
args({ tenant: accepts(v.string()).required(["post", "comment"]) })
);
required: true was asked on the models the extension named in rows,
data or deletion. Nothing is deduced now: list those models in
.required([...]), or leave the list out to ask everywhere. One extension
declares a name once: two args parts of one extension that declare the
same name are refused, as two extensions are.
rows → args and rule
A mode control becomes an argument with a default; each mode’s filters become
when and unless:
// Before
rows: {
control: "archived",
default: "hide",
models: {
project: {
hide: { root: { archivedAt: null }, related: { archivedAt: null } },
show: {},
only: { root: { archivedAt: { not: null } } },
},
},
},
// After
import { arg, args, extension, oneOf, rule, selecting, unless, when } from "viborm";
const db = client.$extends(
extension(
"archiving",
args({ archived: oneOf("hide", "show", "only").default("hide").on(selecting) }),
rule({
project: {
root: [
when(arg("archived"), "hide", { archivedAt: null }),
when(arg("archived"), "only", { archivedAt: { not: null } }),
],
related: unless(arg("archived"), "show", { archivedAt: null }),
},
})
)
);
A filter with no mode is read.where. when applies its filter when the test
holds and lets every row pass otherwise, as a mode did; provided holds only
when the test holds, as $if did.
rows.verbs → the keys of rule
| Earlier verb | Key |
|---|---|
predicates |
Shared constants: two keys share a predicate by sharing the object |
read |
read.where |
update |
update: { where: only(where) } |
delete |
delete: { where: only(where) } |
writes: { f } |
update.fields.f: { where: only(where) }, which replaces update.where for a write of f |
place |
create: { check: check(where) } |
moves: { f } |
update.fields.f: { check: check(where) } |
acyclic |
acyclic |
evidence |
read.select: { $access: facts({ … }) } (no ordered option) |
reads: { f } |
read.fields: { f: gate(where) } |
| an entry given as a function | lazy(() => entry) |
// Before
verbs: {
document: {
predicates: { seen, own },
read: "seen",
update: "own",
reads: { notes: "own" },
},
},
// After
import { accepts, arg, args, check, extension, gate, nothing, only, rule } from "viborm";
import { v } from "viborm/validation";
const seen = { OR: [{ public: true }, { ownerId: arg("user") }] };
const own = { ownerId: arg("user") };
const db = client.$extends(
extension(
"sharing",
args({ user: accepts(v.string()).required(["document"]) }),
rule({
document: {
read: { where: seen, fields: { notes: gate(own) } },
update: { where: only(own), check: check({ AND: [seen, own] }) },
delete: { where: only(nothing) }, // no delete, as the omitted verb meant
},
})
)
);
Two meanings changed:
- A key an entry leaves out adds no restriction. An earlier verb an entry
omitted took no row (no
deleteverb: no delete). Aruleentry withoutdeletelets a call delete every row it can read. To keep the earlier meaning, write a filter that takes no row, as above:delete: { where: only(nothing) }(nothingis{ OR: [] }). - Nothing is implied. An updated row was judged again, implicitly, at the
predicates that let the update take it.
update.checksays what the row an update leaves must hold; it is stated in the statement only when the update writes a field the predicate reads. To keep the earlier meaning, write it with the read predicate and the update predicate, as above.
deletion → keep
// Before
controls: { purge: { oneOf: [true] } },
deletion: {
removeWhen: { purge: true },
models: { project: { at: "archivedAt", assign: { archivedBy: "system" } } },
},
// After
import { arg, args, deletes, extension, keep, now, oneOf, rule, unless } from "viborm";
const db = client.$extends(
extension(
"archiving",
args({ purge: oneOf(true).on(deletes).models(["project"]) }),
rule({
project: {
delete: {
instead: keep(unless(arg("purge"), true, { archivedAt: now, archivedBy: "system" })),
},
},
})
)
);
removeWhen placed its control on the deletes of the managed models; write
that placement yourself with .on(deletes).models([...]).
data and order → defaults
// Before
data: { models: { post: { create: { createdBy: { control: "actor" } } } } },
order: { models: { card: [{ columnId: "asc" }, { rank: "asc" }] } },
// After
import { accepts, arg, args, defaults, extension, writes } from "viborm";
import { v } from "viborm/validation";
const db = client.$extends(
extension(
"house-style",
args({ actor: accepts(v.string()).on(writes) }),
defaults({
post: { create: { createdBy: arg("actor") } },
card: { orderBy: [{ columnId: "asc" }, { rank: "asc" }] },
})
)
);
result → fields
// Before
result: { user: { fullName: { needs: { firstName: true }, compute: (u) => u.firstName } } },
// After
import { extension, fields } from "viborm";
const db = client.$extends(
extension(
"names",
fields({ user: { fullName: { needs: { firstName: true }, compute: (u) => u.firstName } } })
)
);
client and model → methods and modelMethods
Each becomes a part of its own, which brings only its own code:
// Before
client: (scope) => ({ $postCount: () => scope.post.count() }),
model: { post: (delegate) => ({ findPublished: () => delegate.findMany({ where: { published: true } }) }) },
// After
import { extension, methods, modelMethods } from "viborm";
const db = client.$extends(
extension(
"post-tools",
methods((scope) => ({ $postCount: () => scope.post.count() })),
modelMethods((scope) => ({
post: {
findPublished() {
return scope.post.findMany({ where: { published: true } });
},
},
}))
)
);
A model method is called with this set to its delegate, so a model factory
that received the delegate can become a method that reads this. A factory
that takes scope is a result consumer, as a typed factory was: TypeScript
refuses a later rule that hides rows or a later omission. Type a model method
through this and DelegateOperationResult and take no scope to avoid that
(methods).
Spelled values → words
| Earlier | Now |
|---|---|
{ control: "tenant" }, { control: "actor", path: "userId" } |
arg("tenant"), arg("actor", "userId") |
{ now: true } |
now |
{ $row: "orgId", up: 1 } |
row("orgId", 1) |
{ $exists: { member: where } } |
exists({ member: where }) |
{ $if: { control, path, in: [...] } } |
provided(arg(control, path), { in: [...] }, filter?) |
A word is a value, never detected: { control: "x" } is now a filter on a
field named control, as any other object.
What goes without replacement
- The object literal passed to
$extends(),defineHooks,enableExtensions, and a function of the client passed to$extends(). - The refusal “nothing brought the code that runs extensions” or “that reads
rows”: every part brings its own code. - Reading a definition as hostile data: proxies, accessors that throw, symbol keys, frozen copies of the definition. A definition is trusted code.
- The aggregated error when both the child and the handler fail: the child’s error stands.
- Core containment of observers. A
unitthat throws fails the call. observes, and its rule of one per client.- Named predicates (
verbs.predicates), andfacts’orderedoption. - The implicit judgement of an updated row (write
update.check), and therequiredplacement deduced fromrows,dataanddeletion(list the models). warn, thewarninglog level,prewarm, and the types of the earlier definition: fromviborm,ClientExtension,MergeExtensionState,ObservationCompletion,ObservationFacts,ObservationNeed,ObservationUnit,ObservedFacts,ObserveHandler,ObservesDeclaration,RetryHandler,RouteHandler,StatementContext,StatementHandler,TransactionHandler,UnitCall,WrittenCall,WrittenHandlerandWrittenWatch; fromviborm/client, those of them it exported, andDefinitionControlsandRowsVerbs.PlacedControlisPlacedArgumentandNoControlsisNoArguments.- One default omission per client: the omissions of different extensions
written with
defaultsandomittednow add up per model.defaultOmit()itself is one extension, applied once per chain.
Users of the official extensions
Every official extension is applied in one step:
client.$extends(official(config)).
// Before
const db = softDelete(config)(base);
const db2 = ordering(config)(base);
const db3 = base.$extends(softDelete(config).rows).$extends(policy).$extends(softDelete(config).methods);
const db4 = base.$extends(defaultOmit<typeof schema>()({ user: { passwordHash: true } }));
// After
import { defaultOmit } from "viborm/client";
import { ordering } from "viborm/ordering";
import { softDelete } from "viborm/soft-delete";
const db = base.$extends(softDelete({ models: { post: { deletedAt: "deletedAt" } } }));
const db2 = base.$extends(ordering({ models: { card: { key: "rank" } } }));
const db3 = base
.$extends(softDelete({ models: { post: { deletedAt: "deletedAt" } } }))
.$extends(policy);
const db4 = base.$extends(defaultOmit({ user: { passwordHash: true } }));
softDelete(config).rowsandsoftDelete(config).methodsare gone, and so is applying an official extension as a function of the client. A chain that applied steps as functions (methods(policy(rows(base)))) becomes successive$extends()calls.defaultOmit<typeof schema>()(config)isdefaultOmit(config), typed against the client it is applied to. A chain applies it once: it is the extensionviborm.defaultOmit, and a second is refused when it is applied as any extension applied twice (Extension "viborm.defaultOmit" is already present on this client.): merge the two configs. Another extension that omits fields withdefaultsadds to it per model.instrumentation()no longer takes alogging.warninglevel: nothing produced warnings.- The cache: a read that carries a
.volatile()argument through$withCache()runs without being served or stored instead of being refused. Reads are keyed by the statement they send.tx.$withCache()andtx.$invalidate()exist in an interactive transaction. A backend that fails during$invalidate()is aCacheConfigurationError. Stale-while-revalidate comes with a value the cache is configured with,cache({ driver, swr: staleWhileRevalidate })(viborm/cache): a view’sswroption on a cache configured without it is aCacheConfigurationError. A driver’s unscoped storage is reached through functions ofviborm/cache:driver._get(key)isgetEntry(driver, key), and_set,_delete,_clear,_invalidate,_markRevalidatingand_clearRevalidatingaresetEntry,deleteEntry,clearEntries,invalidateEntries,markRevalidatingandclearRevalidating. viborm/permissions: five forms of its policy language are gone, and so arecanandassert(read$accessinstead); see Permissions.- Error texts changed throughout: match on the error’s class and code.