@open-apiary/schema
v0.0.8
Published
The authoring API: the endpoint builder, the exception, the operation id, and the types of a manifest and a bundle. The package has no runtime of its own. The public [`open-apiary`](../open-apiary) package re-exports it.
Readme
@open-apiary/schema
The authoring API: the endpoint builder, the exception, the operation id, and
the types of a manifest and a bundle. The package has no runtime of its own. The
public open-apiary package re-exports it.
Install
pnpm add open-apiary zodEndpoints
apiary has one function for each method: GET, POST, PUT, PATCH,
and DELETE. Each takes the route, the validators of the input, and the
validator of the output. The route is an OpenAPI path. A path validator
has one member for each parameter of the route. GET and DELETE take no
body and no form.
import { apiary, ConflictException } from "open-apiary";
import { z } from "zod";
export default apiary
.POST("/users", { body: NewUser }, User)
.handle(async (_ctx, input) => users.create(input.body))
.withStatus(201)
.withExceptions(ConflictException)
.withScopes("users:write")
.withTags("users")
.withSpec({ summary: "Create a user" });Forms
An endpoint that takes a form names a form validator in place of body:
an object with one member for each field. An endpoint has one of the two,
and not both.
export default apiary
.POST(
"/avatars",
{
form: z.object({
name: z.string(),
size: z.coerce.number().optional(),
tags: z.array(z.string()).default([]),
image: z.file().mime(["image/png", "image/jpeg"]),
}),
},
Avatar,
)
.handle((ctx, input) =>
ctx.resolve(AvatarsContract).store(input.form.name, input.form.image),
);The request is a
multipart/form-databody, or anapplication/x-www-form-urlencodedone. The OpenAPI document lists both, andmultipart/form-dataalone when a field is a file.A field arrives as text, so a number needs
z.coerce, as in a query.A file is a
z.file(), and the handler reads aFile.A field that repeats is a
z.array(). One value is a list of one.A request with any other body, such as JSON, is a 415: the endpoint may answer with
UnsupportedMediaTypeException, with nowithExceptions.handlesets the handler. It receives the context and the parsed input. The context has thecaller, theendpoint, andresolve, which returns the provider of a contract.apiary.contract<T>(key)makes a contract, and a class underproviders/fills it. The handler gets everything else by import. It returns a value that the output validator accepts. The types follow the validators.withAuthrequires a caller, with no scope. The core answers with a 401 for a request with none, and the kit lists the scheme undersecurity.withScopessets the scopes a caller needs, and so requires a caller. The core checks them, and answers with a 403 for a caller without them. The kit lists them undersecurity.A handler that
handletakes afterwithAuthorwithScopeshas actx.callerthat is always there. In a handler before them, and in one of an endpoint that requires no caller, it may beundefined.An API adds the members of a caller to the
Callerinterface once, withdeclare module "open-apiary" { interface Caller { … } }, and every handler reads them typed.An API declares its scopes once, with
declare module "open-apiary" { interface Vocabulary { scope: … } }, andwithScopestakes no other. Without the declaration it takes any string.withStatussets the success status. The default is 200, and 201 forPOST.withExceptionsdeclares the exceptions that the endpoint may answer with: the classes of them. The kit lists each one underresponses, and the core answers with a 500 for an error that is not among them.withTagsandwithSpecextend the OpenAPI operation.withSpecmerges over what the kit infers.operationIdreplaces the derived id.
Each method returns a new endpoint. The definition is under the
DEFINITION symbol. isEndpoint tests for it.
Exceptions
apiary.exception(code, status, options) makes the class of an exception. A
handler, or a provider under it, throws one, and the response is a problem
details object, as RFC 9457
defines it.
export class UserNotFound extends apiary.exception("user_not_found", 404, {
extensions: z.object({ id: z.uuid() }),
}) {}
throw new UserNotFound({ id }, "no user has this id");| Member | In the problem |
| ------------ | -------------------------------------------------------------------------------- |
| code | code. It names the exception, and is unique in an API. |
| status | status, and the status of the response. From 400 to 599. |
| title | title. The default is the reason phrase of the status. |
| type | type. The default is about:blank. Set it when a URI documents the exception. |
| extensions | One member for each member of the validator. None can replace a member above. |
The constructor of a class with no extensions takes the detail of the
throw. One with extensions takes them first, then the detail. The detail is
the detail of the problem, and is absent when the throw gives none.
The package has a class for each common status, with no extensions:
BadRequestException, UnauthorizedException, PaymentRequiredException,
NotFoundException, MethodNotAllowedException, NotAcceptableException,
RequestTimeoutException, ConflictException, GoneException,
PreconditionFailedException, ContentTooLargeException,
UnsupportedMediaTypeException, RangeNotSatisfiableException,
UnprocessableContentException, LockedException, FailedDependencyException,
PreconditionRequiredException, TooManyRequestsException,
UnavailableForLegalReasonsException, NotImplementedException,
BadGatewayException, ServiceUnavailableException, GatewayTimeoutException, and
InsufficientStorageException.
A class declares the headers of its response with headers, a validator
of each by its name in lower case. A throw gives them after the extensions
and before the detail, and the OpenAPI document lists them under the
response of every endpoint that declares the class.
export class QuotaExceeded extends apiary.exception("quota_exceeded", 429, {
headers: z.object({ "retry-after": z.string() }),
}) {}
throw new QuotaExceeded({ "retry-after": "3600" }, "the quota is spent");Five classes of the package declare one:
| Class | Header | Required |
| ------------------------------ | ------------------ | -------- |
| UnauthorizedException | www-authenticate | No |
| MethodNotAllowedException | allow | Yes |
| RangeNotSatisfiableException | content-range | Yes |
| TooManyRequestsException | retry-after | Yes |
| ServiceUnavailableException | retry-after | No |
The core answers with four of its own:
| Class | Status | Answered |
| ----------------------- | ------ | ------------------------------------------------------------------------ |
| InvalidInputException | 400 | When a part of the input fails its validator. errors lists the issues. |
| UnauthorizedException | 401 | When the endpoint requires a caller and the request has none. |
| ForbiddenException | 403 | When the caller lacks a scope of the endpoint. scopes lists them. |
| InternalException | 500 | For every error that the endpoint does not declare. |
With no withExceptions, an endpoint with a validator may answer with the
first, one that requires a caller with the second, and one with scopes with
the third. exceptionsOf(definition) lists what an
endpoint may answer with, isApiaryException tells an exception of an API from any
other, and problemOf makes the problem of one.
Providers
Provider is the optional base class of a provider. It holds the context of
its constructor as this.ctx, and reads the log of the API from it as
this.log: the provider under LogContract, whose interface is Log. The
core provides a class under it: see @open-apiary/core.
Operation ids
identify(method, route) derives the operation id of an endpoint:
GET /users/{id} is getUsersById. operationId(definition) returns the
operationId of withSpec when the endpoint sets one, else the derived id.
The kit names the route module of an endpoint with it, and the core reports
it as ctx.endpoint.id.
Types
Manifestis whatapiary buildwrites asmanifest.json: the data of each endpoint, with no validator and no handler.Bundleis the default export of a built package: each endpoint by operation id, as its manifest entry and aloadthat imports its route module.RouteModuleis a route module. Its default export is the endpoint.
