apigenie-generator server orpc

Tier 2 · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · Verification

Generate a TypeScript server based on oRPC from an OpenAPI document.

Usage

apigenie-generator server orpc [...OPTIONS] INPUT_FILE

Description

The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see Swagger 2.0 input); bundle documents referencing other files with apigenie bundle.

Every operation becomes an oRPC procedure, with Zod (v4) schemas validating its input and output. The generated npm package contains:

File Content
src/schemas.ts Zod schemas, with their types, of the components, bodies, inputs and outputs
src/contract/<group>.ts the contract of each procedure: route, input, output and errors
src/contract/index.ts the contract router, by group
src/handlers/<group>.ts a handler per procedure, throwing NOT_IMPLEMENTED
src/orpc.ts the context of the procedures and implement(contract)
src/router.ts the router assembling the handlers
src/server.ts a Node.js HTTP server with oRPC’s OpenAPIHandler
src/main.ts starts the server on the port in PORT (3000 by default)
src/senders.ts createWebhooks() and createCallbacks(), when the document has webhooks or callbacks
src/outgoing.ts the module sending their requests, shared with the Express server
src/index.ts exports of the package

Procedures are grouped by the first tag of their operations, or the first segment of their paths, and named after their operationIds.

The handlers, orpc.ts, server.ts, main.ts, package.json and tsconfig.json are meant to be edited, and are only written when they don’t exist. Regenerating updates the schemas, the contract, the router and the senders (senders.ts, outgoing.ts); the TypeScript compiler then reports the handlers that new operations need.

apigenie-generator server orpc openapi.yaml -o server
cd server && npm install && npm run dev

The server answers the operations under the path of the first server of the document (e.g. /v1), and serves its OpenAPI document at /spec.json and an API reference at /. Operations with servers of their own (operation or path item servers) with another path, e.g. a health check on the root of a status host, are also answered at that path.

Inputs and outputs

A procedure receives the path parameters merged with the query parameters (GET) or the body (other methods), oRPC’s compact input structure, unless that would lose part of the request: operations with header or cookie parameters, query parameters in other methods than GET, or bodies which can’t be merged with the path parameters get the detailed structure, with params, query, headers (in lower case) and body. Parameters are converted from strings to the types of their schemas, and array parameters accept repeated values, a single value, and the delimited values of the form (with explode: false), spaceDelimited and pipeDelimited styles. Cookie parameters are read from the Cookie header (headers.cookie), parameters described by content: application/json are parsed as JSON, and a path segment of several parameters, such as /labels/{labelId}.{extension}, is routed as one parameter and split into its parameters.

The body is read in any of the operation’s media types:

  • JSON bodies, including other JSON media types such as application/merge-patch+json, which the server parses before oRPC, and JSON Lines, which the procedure receives as an array;
  • application/x-www-form-urlencoded and multipart/form-data bodies, whose fields are converted to the types of their schemas (an empty field is null where the schema allows it) and whose binary parts are Files;
  • text/plain bodies as strings, other text and binary bodies as Files.

A procedure returns the body of its response. When an operation has success responses with different bodies, or response headers, it returns { status, headers, body } objects instead. JSON bodies are objects; other bodies (text, files) are Blobs, which the server sends with their media type. A text/event-stream response is an eventIterator() of its itemSchema (the contentSchema of the events’ data, or the item of the operation’s JSON Lines response); when the operation also answers JSON, the handler returns either a value or an async iterator, as the client accepts. The writeOnly properties of a response are left out of what the server sends, and the readOnly properties of a request out of what the handler receives.

A oneOf with a discriminator and a defaultMapping (x-defaultMapping in 3.0 and 3.1 documents) validates the option its property selects, or the default one; closed allOf compositions (unevaluatedProperties: false) reject properties none of their schemas declare.

Each 4xx and 5xx response becomes an error of the procedure: NOT_FOUND, CONFLICT and the other codes of oRPC, or HTTP_<status> for other statuses. 4XX and 5XX ranges become the errors of their first status (BAD_REQUEST, INTERNAL_SERVER_ERROR), and a default response next to success responses INTERNAL_SERVER_ERROR, unless the document declares those statuses. Their response bodies are their data, which the server sends as the body of the response:

throw errors.NOT_FOUND({ data: { code: 404, message: "No such pet" } });

Not supported, and reported as warnings: path parameters in other styles than simple, object query parameters in the form style (read in the deepObject style), and OPTIONS and CONNECT operations, which are skipped. The CORS plugin answers every OPTIONS request with 204 before routing, and Node.js doesn’t pass CONNECT requests to the server’s handler.

Since 0.12.0, operations with methods other than GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS and CONNECT are also routed. Examples are QUERY and an additionalOperations COPY. oRPC routes any method, but the method type of its routes lists only the first six, and QUERY in oRPC 2. The contract declares the other methods with a cast: method: "COPY" as HTTPMethod in oRPC 1, method: "COPY" as NonNullable<OpenAPIMeta["method"]> in oRPC 2. The CORS plugin adds them to the methods it allows in its answer to a preflight. Node.js parses only the methods in http.METHODS, which include COPY, the other WebDAV methods and, in recent versions, QUERY. It answers a request with any other method with 400 Bad Request before oRPC sees it. oRPC’s /spec.json is an OpenAPI 3.1.1 document, which has no other methods: it lists these operations under keys such as copy and query, which 3.1 validators reject.

oRPC streams async iterators as server-sent events only, so a JSON Lines response is answered as a Blob the handler builds.

Webhooks and callbacks

Since 0.12.0, the requests your application sends are generated too. They are the webhooks of the document (x-webhooks in OpenAPI 3.0 documents) and the callbacks of its operations. src/senders.ts then has createWebhooks(options), createCallbacks(options) or both, whose senders send each request with fetch:

// src/handlers/shipments.ts
import { os } from "../orpc.js";
import type { ShipmentStatusChangedEvent } from "../schemas.js";
import { createCallbacks, createWebhooks } from "../senders.js";

const webhooks = createWebhooks({ headers: { "User-Agent": "carpet-express" } });

export async function notify(url: string, event: ShipmentStatusChangedEvent) {
  await webhooks.onShipmentStatusChanged(url, {
    headers: { "CarpetExpress-Signature": sign(event) },
    body: event,
  });
}

const callbacks = createCallbacks();
export const createShipment = os.shipments.createShipment.handler(async ({ input }) => {
  const shipment = await db.shipments.create(input.body);
  queue.onStatusChange(shipment, async (event) => {
    const response = await callbacks.createShipment.statusChanged(
      { request: input },
      { headers: { "CarpetExpress-Signature": sign(event) }, body: event },
    );
    if (response.status === 410) {
      queue.stop(shipment);
    }
  });
  return { status: 201, headers: { etag: etag(shipment) }, body: shipment };
});

A webhook sender is named like a procedure, from the sources action_naming lists, or else after its method and name, and takes the subscriber’s URL. A callback sender is grouped under the procedure that declares the callback. It is named after the callback, followed by the method when the callback has several requests.

A sender’s request and response are typed in src/schemas.ts as <Name>Request and <Name>Response. <Name> is the name of a webhook sender in PascalCase. For a callback, it is the name of the callback component it refers to when no other callback refers to it (ShipmentStatusCallbackRequest). Otherwise it is the procedure name and the callback name (CreateWebhookSubscriptionVerificationRequest). The method follows when the callback has several requests. A request has the query, headers and cookies parameters by name, the body, and the contentType of the body, the first declared media type by default.

A callback sender takes a source, against which the runtime expressions of the callback’s URL, such as {$request.body#/callbackUrl}, are resolved. Its request is the procedure’s input as { params, query, headers, body }. A compact input merges the path parameters with the body or the query. Pass it as body for $request.body expressions. Pass the parameters that $request.path and $request.query expressions read as params and query. Its optional response is the output as { status, headers, body }, with a compact output as body. source.request is typed as the input the handler receives. source.response is typed as the value the handler returns, before the output schema parses it, so the schema’s defaults aren’t applied: a $response.body expression that reads a field the handler leaves out resolves to nothing. The optional url, method and headers of source are those of the HTTP request, for $url, $method and the headers the input doesn’t hold. The generated context has the headers (context.headers); $url and $method need the URL and method added to Context in src/orpc.ts.

A sender validates the parameters and a JSON, form or text body with the Zod schemas of OUTGOING_SCHEMAS (src/schemas.ts). It also rejects a contentType the operation doesn’t declare. On a failed check it rejects with an InvalidRequestError instead of sending the request. It resolves with the response, typed per declared status as { status, body, headers, contentType }, and checks a JSON or text body against its Zod schema. How it serializes the request, resolves the URL, decodes the response and rejects with an UnexpectedResponseError is described for the Express server’s senders: both use src/outgoing.ts.

The options of createWebhooks and createCallbacks:

Option Description
fetch The function sending the requests; globalThis.fetch by default
validation Checks the requests and responses; outgoingValidation, with the Zod schemas, by default
headers Headers of every request, e.g. a User-Agent
onRequest(request, operation) Called with each Request before it’s sent, e.g. to sign it; returns the request to send

Each sender also takes the headers and the signal of one request as its last argument. OUTGOING_OPERATIONS in src/senders.ts describes the webhooks and callbacks; onRequest receives its entry as operation. The path of a webhook is its name, and that of a callback its URL expression.

Extensions

Extension Effect
x-apigenie.codegen.name name of the schema and type of a component schema (AnimalSchema, Animal)
x-apigenie.codegen.action-name name of the procedure of an operation, or of the sender of a webhook, when action_naming lists extension
x-webhooks webhooks of an OpenAPI 3.0 document: the requests the senders of src/senders.ts send

The extensions can live in an overlay for this target instead of in the document, e.g. orpc.overlay.yaml:

overlay: 1.0.0
info:
  title: TypeScript names
  version: 1.0.0
actions:
  - target: $.components.schemas.Pet
    update:
      x-apigenie:
        codegen:
          name: Animal
apigenie-generator server orpc openapi.yaml --overlay orpc.overlay.yaml -o out

Options

-c, –config

Path to the configuration file to use. See the “Configuration” section for more information.

–overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the “Extensions” section. Can be repeated: the overlays apply in order, after those listed under commands.generate.server_orpc.overlay in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay.

–strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.).

–check

Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See Check that generated code is up to date.

-o, –output

Directory where the package is generated.

–package-name

Name of the package, <title>-server by default.

–package-version

Version of the package, the version of the API by default.

Configuration

version: '1.0'
commands:
  generate:
    server_orpc:
      orpc_version: 1
      input_structure: auto
Option Description
orpc_version 1 (default) for oRPC 1, 2 for oRPC 2 (beta): routes declared with oc.meta(openapi(...)) and queryStyles
input_structure auto (default), compact (header parameters, and query parameters of other methods than GET, are dropped) or detailed
layout package (default) for an npm package, sources for the sources only
import_extension extension of relative imports: .js (default, Node.js) or "" (bundlers)
action_naming sources of procedure and webhook sender names, in order: id (operationId), extension (x-apigenie), url; [id, url] by default
additional_properties loose (default) keeps the properties of objects their schemas don’t list, strip removes them
describe true attaches the descriptions of schemas with .describe() (default: false)

Verification

The codegen conformance suite runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. All targets.

This target's support tier is Tier 2. It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives.

ResultsLevel 1Level 2Level 3
Release 0.12.0✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, oRPC 1)✓ 72 of 77 operations pass (node)
Development version✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yetruns before a releaseruns before a release
Was this helpful?