@open-apiary/core
v0.0.8
Published
The runtime. `makeApiary` makes the engine of an API over the bundle that `apiary build` wrote. `invoke` calls one endpoint, and the engine runs it for each call. Neither does HTTP. The public [`open-apiary`](../open-apiary) package re-exports both.
Readme
@open-apiary/core
The runtime. makeApiary makes the engine of an API over the bundle that
apiary build wrote. invoke calls one endpoint, and the engine runs it
for each call. Neither does HTTP. The public open-apiary
package re-exports both.
Install
pnpm add open-apiary zodThe engine
import bundle from "@acme/api";
import document from "@acme/api/openapi.json" with { type: "json" };
import { makeApiary } from "open-apiary";
const apiary = makeApiary(bundle, { document });| Member | Description |
| --------------------------- | --------------------------------------------------------------------------------------------- |
| endpoints | The data of each endpoint: id, method, route, status, scopes, tags. A read loads no endpoint. |
| endpoint(id) | The data of one endpoint. |
| load(id) | Loads one endpoint. The first call imports its route module. A failed load runs again. |
| invoke(id, raw, caller) | Loads the endpoint and runs invoke on it. The body is typed from the bundle. |
| respond(id, raw, caller) | As invoke, but every error becomes a status and a problem details object. See below. |
| document | The OpenAPI document of the options, for the integration to serve. |
| check() | Throws UnfilledContractsError when a contract of the bundle has no class. |
| register(contract, Class) | Puts a class under a contract, in place of the one of the bundle. For a test. |
| dispose() | Disposes the singletons that the calls built. A server calls it when it shuts down. |
The options are authorize, the authorization function of every call,
document, container, which replaces the container that the engine
makes, onError, which takes each error that respond answers with a
500 for, and challenge, the WWW-Authenticate of a 401, such as
Bearer. An id that the bundle lacks is an UnknownEndpointError. A
route module whose default export is not an endpoint is an
InvalidRouteModuleError.
A framework integration is a wrapper around the engine. It registers one
route for each entry of endpoints, turns a request into a raw input and a
caller, calls respond, and sends the status, the headers, and the body.
respond answers as HTTP does, and throws for nothing but an id that the
bundle lacks:
- An exception that the endpoint may answer with is its status and its problem
details object, as RFC 9457 defines it, with the header
content-type: application/problem+json. These are the classes ofwithExceptions,InvalidInputExceptionfor an endpoint with a validator,UnauthorizedExceptionfor one that requires a caller, andForbiddenExceptionfor one with scopes. A 401 has thechallengeof the options as itswww-authenticateheader, when the options have one. The class that the endpoint declares sets the status, the title, and the type, so the answer is what the document says. The headers that the class declares go with it, such as theretry-afterof a 429. - Any other error is a 500 whose problem says nothing of the cause: an
error that is no
ApiaryException, anApiaryExceptionthat the endpoint does not declare, extensions that the class of the exception rejects, an output that fails its validator, or a route module that fails to load.
onError(error, { id, caller }) takes each error of the second kind. An
undeclared ApiaryException comes inside an UndeclaredExceptionError, and rejected
extensions inside an InvalidExtensionsError, rejected headers inside an
InvalidHeadersError, each with the exception of the
handler as its cause. The default writes the error to the log of the
API, as an errors.unhandled entry. See The log.
const apiary = makeApiary(bundle, {
onError: (error, { id }) => logger.error({ err: error, endpoint: id }),
});One endpoint
import getUser from "@acme/api/routes/getUsersById";
import { invoke, isApiaryException } from "open-apiary";
try {
const { status, body } = await invoke(
getUser,
{ path: { id: "42" }, query: {}, headers: {} },
{ scopes: ["users:read"] },
{
authorize: (caller, scopes) =>
scopes.every((s) => caller.scopes.includes(s)),
},
);
} catch (error) {
if (isApiaryException(error)) {
// error.status, error.code, error.detail, error.extensions
}
}invoke runs these steps:
- It checks that an endpoint that requires a caller has one: the caller is
undefinedfor a request with none. A failure isUnauthorizedException, status 401. Then it checks the scopes of the endpoint against the caller withauthorize. A failure isForbiddenException, status 403. The default requires every scope of the endpoint in the scopes of the caller. - It parses
path,query,headers, andbodyorformwith the validators of the endpoint. A missingpath,query, orheadersis an empty object. Theformof the input is aFormData, or an object with one member for each field. An endpoint with aformvalidator and an input with no form isUnsupportedMediaTypeException, status 415. A failure isInvalidInputException, status 400. Itserrorsextension lists the issues of every part: where the value is (in), its JSON Pointer (pointer), and what is wrong with it (detail). - It opens a lifetime of the container and runs the handler with a context:
caller,endpoint, andresolve. - It disposes the lifetime, and with it each per-lifetime provider that the handler resolved, whether the handler returned or threw.
- It parses the value with the output validator. A failure is
InvalidOutputError, which is noApiaryException: the fault is in the API.
The result is { status, body }. The body is typed from the output
validator of the endpoint. invoke checks no exception against withExceptions:
an ApiaryException from the handler propagates as it is, and so does any
other error. respond is what turns them into answers.
Providers
A handler imports the code that it runs the same way everywhere. What it gets by name is a provider: a contract names it, a class fills the contract, and the handler resolves it.
// src/contracts/users.ts
export const UsersContract = apiary.contract<Users>("users");
// src/providers/users.ts
export default class MemoryUsers implements Users {
static readonly contract = UsersContract;
find(id: string) { … }
}
// src/endpoints/users/get.ts
export default apiary
.GET("/users/{id}", { path: Id }, User)
.handle((ctx, input) => ctx.resolve(UsersContract).find(input.path.id));The build writes the classes of the API and of its presets to the bundle,
in the order of the layers, and makeApiary provides each one to the
container. A later class takes the contract of an earlier one. A server
registers nothing:
const engine = makeApiary(bundle);The bundle also lists the key of each contract. check() throws
UnfilledContractsError, with every key that no class fills. An
integration calls it when it mounts the engine, and each invoke and
respond runs it until it passes, so an open contract is an error at
startup and not at the first resolve of it.
register puts a class under a contract in place of the one of the
bundle. It is for a test, which sets a fake where the provider was:
const engine = makeApiary(bundle).register(UsersContract, FakeUsers);A class is a singleton unless it has static readonly perLifetime = true. A
singleton is built at the first resolve and kept until dispose(). A per-lifetime
provider is built once for each call that resolves it, takes the context of
the call in its constructor, and is disposed when the handler ends. A
provider that holds a resource has a dispose method. The lifetimes, the
errors, and the container itself are in
@open-apiary/container.
The log
Every API has a class under LogContract, with no code of its own:
makeApiary provides StdoutLog, which writes one line of JSON on the
standard output for each entry, with its level, its time, its
message, and the members of its data.
A provider that extends Provider has the log as this.log:
import { NotFoundException, Provider } from "open-apiary";
export default class MemoryUsers extends Provider implements Users {
static readonly contract = UsersContract;
get(id: string): User {
const user = this.users.get(id);
if (user === undefined) {
this.log.warn("users.missing", { id });
throw new NotFoundException(`no user with id ${id}`);
}
return user;
}
}A handler has it on its context, as ctx.log:
.handle((ctx, input) => {
ctx.log.info("users.read", { id: input.path.id });
return ctx.resolve(UsersContract).get(input.path.id);
})Provider is optional: any class with a static contract is a provider. A
per-lifetime provider extends Provider<Context> and reads the call from
this.ctx. A subclass with a constructor passes the context on with
super(ctx).
StdoutLog writes no entry under info. A subclass sets another level
with protected override readonly level = "debug".
An API replaces the log as it fills any contract: a class under
providers/ whose static contract is LogContract. The log is a
singleton, so that a singleton can hold it: a per-lifetime class under the
contract is a CaptiveProviderError.
invoke on one endpoint takes the container as an option:
invoke(endpoint, raw, caller, { container }). Without one, no contract
resolves but the log, which invoke provides to any container that lacks
one.
