Skip to Content

Decorators

The decorator half of modules/openapiv3.js. It describes what a resource’s HTTP methods do, and turns those descriptions into the paths member of an OpenAPI Specification v3  (OAS v3) document.

To generate a whole document without writing the assembly yourself, see the CLI.

Summary

This module exports the OpenAPIv3 decorator  — a marker you attach to a resource’s HTTP method with @ syntax. It records something about the HTTP method without changing what it does. Here it records an OAS v3 Operation Object: the description of one HTTP method on one path, including what it accepts and what it can respond with.

Nothing happens at request time. The description is stored, and read back later to build the paths member of an OAS v3 document you can write out as YAML or JSON.

A complete, runnable example:

app.ts
import { Resource, } from "@drashland/drash/modules/http.native.js"; import { buildPathsObject, OpenAPIv3, } from "@drashland/drash/modules/openapiv3.js"; import { stringify as yamlStringify } from "jsr:@std/yaml"; class Users extends Resource { paths = ["/users/:id?"]; @OpenAPIv3({ summary: "Get a user", tags: ["users"], responses: { "200": { description: "The user", content: { "application/json": { schema: { type: "object" }, }, }, }, }, }) GET(request: Request) { return new Response(`Getting ${request.params.pathParam("id")}`); } } // The `paths` member of an OAS v3 document, derived from the resource. const document = { openapi: "3.0.3", info: { title: "My API", version: "1.0.0" }, paths: buildPathsObject([Users]), }; console.log(JSON.stringify(document, null, 2)); console.log() console.log(yamlStringify(document));

Run it with the following to print the OAS v3 document in JSON:

Terminal
deno run app.ts

Click here to see the printed OAS v3 document in JSON

{ "openapi": "3.0.3", "info": { "title": "My API", "version": "1.0.0" }, "paths": { "/users": { "get": { "summary": "Get a user", "tags": [ "users" ], "responses": { "200": { "description": "The user", "content": { "application/json": { "schema": { "type": "object" } } } } } } }, "/users/{id}": { "get": { "summary": "Get a user", "tags": [ "users" ], "responses": { "200": { "description": "The user", "content": { "application/json": { "schema": { "type": "object" } } } } }, "parameters": [ { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } } ] } } } }

Click here to see the printed OAS v3 document in YAML

openapi: 3.0.3 info: title: My API version: 1.0.0 paths: /users: get: summary: Get a user tags: &ref_0 - users responses: &ref_1 '200': description: The user content: application/json: schema: type: object '/users/{id}': get: summary: Get a user tags: *ref_0 responses: *ref_1 parameters: - name: id in: path required: true schema: type: string

The rest of this page takes that apart.

A resource is the class that answers requests for one or more paths, and its GET, POST, and other methods handle those HTTP methods. See Creating a Resource if you have not written one yet.

The Decorator

@OpenAPIv3({ ... }) takes one argument: an Operation Object. Its fields are the ones the OAS v3  defines, so anything valid there is valid here.

FieldTypeWhat it is
tagsstring[]Groups the operation under a heading in viewers
summarystringOne line describing the operation
descriptionstringThe long form; CommonMark is allowed
operationIdstringA name for the operation, unique per document
parametersParameterObject[]Path, query, header, and cookie parameters
requestBodyRequestBodyObjectThe body the operation accepts, keyed by content type
responsesResponsesObjectWhat it can respond with, keyed by status code
deprecatedbooleanMarks the operation as no longer recommended
securitySecurityRequirementObject[]Which security schemes apply
serversServerObject[]Servers for this operation, if not the default
externalDocsExternalDocumentationObjectA link to more documentation
callbacksRecord<string, CallbackObject>Requests this operation may make later

Two nuances of the OAS that you should be aware of:

  • Status codes are strings, not numbers. "200", not 200. The wildcard forms ("2XX") and "default" are also allowed.
  • responses is required by OAS v3. Drash makes this optional in this decorator so you can annotate a resource a piece at a time, but an OAS v3 document assembled from operations that have no responses block will not validate.

Where It Can Go

The decorator only makes sense on a resource’s HTTP methods. The decorator will error if placed incorrectly rather than failing quietly. Each of these throws a TypeError when the class is defined:

Written onMessage
A method that is not an HTTP methodOpenAPIv3: `search` is not an HTTP method. Decorate one of: CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE.
A static methodOpenAPIv3: can only decorate an instance method, but `GET` is static.
A #private methodOpenAPIv3: can only decorate a public method, but `GET` is private.
Anything that is not a methodOpenAPIv3: can only decorate a method, but was used on a field.

The private case is a real limitation rather than a style rule: a private method cannot be reached from the class’s prototype, so nothing could read the description back off it.

These are TC39 stage 3 decorators , the standard form, which TypeScript 5 and later compile by default. If your project sets "experimentalDecorators": true in its tsconfig.json, turn it off — that flag selects an older, incompatible decorator design.

Reading a Description Back

getOperation(method)

Returns the Operation Object a single method was decorated with, or undefined if it was never decorated.

import { Resource } from "@drashland/drash/modules/http.native.js"; import { getOperation } from "@drashland/drash/modules/openapiv3.js"; class Users extends Resource { paths = ["/users/:id?"]; @OpenAPIv3({ summary: "Get a user", tags: ["users"], responses: { "200": { description: "The user", content: { "application/json": { schema: { type: "object" }, }, }, }, }, }) GET(request: Request) { return new Response(`Getting ${request.params.pathParam("id")}`); } } getOperation(Users.prototype.GET); // The object passed to @OpenAPIv3 getOperation(Users.prototype.DELETE); // undefined -- not decorated

getOperations(ResourceClass)

Returns every description on a resource, keyed by HTTP method name. Methods that were not decorated are omitted rather than undefined.

import { Resource } from "@drashland/drash/modules/http.native.js"; import { getOperation } from "@drashland/drash/modules/openapiv3.js"; class Users extends Resource { paths = ["/users/:id?"]; @OpenAPIv3({ summary: "Get a user", tags: ["users"], responses: { "200": { description: "The user", content: { "application/json": { schema: { type: "object" }, }, }, }, }, }) GET(request: Request) { return new Response(`Getting ${request.params.pathParam("id")}`); } POST(request: Request) { return new Response("Not decorated, so it is omitted in the OAS document") } } getOperations(Users); // { GET: { summary: "Get a user", ... } }

It walks the prototype chain, so a resource inherits a decorated method from a base class. An override that is not itself decorated counts as undocumented: a different implementation should not inherit the parent’s description.

Building the Paths

buildPathsObject(resources)

Takes resource classes and returns the paths member of an OAS v3 document — every path each resource answers to, with an entry per decorated method.

import { buildPathsObject } from "@drashland/drash/modules/openapiv3.js"; // // code shortened for brevity // const paths = buildPathsObject([Users, Home]);

Resources with no decorated methods contribute nothing, so adding this to an existing application describes only what you have annotated so far.

It returns the paths member alone. A document also needs openapi and info at minimum, which is why the example at the top of this page wraps the result.

Path Parameters

Drash and OAS v3 write path parameters differently, so buildPathsObject translates between them.

Drash matches requests with URLPattern, where a parameter is :id and a trailing ? makes it optional. OAS v3 uses {id}, and a path parameter there is always required.

Resource pathBecomes
/users/users
/users/:id/users/{id}
/users/:id?/users and /users/{id}

An optional parameter has no single OAS v3 equivalent, so it expands into two paths — which is how those two URLs are expressed in a document.

By default, each derived parameter is added with required: true and a string schema. If you describe the same parameter yourself, yours overwrites the default, so you can give it a schema or a description:

class Users extends Resource { paths = ["/users/:id"]; @OpenAPIv3({ summary: "Get a user", parameters: [ { name: "id", // Same name as the path parameter in: "path", required: true, description: "The user's ID", schema: { type: "integer", format: "int64" }, }, ], responses: { "200": { description: "The user" } }, }) GET(request: Request) { // ... } }

Writing the YAML

buildPathsObject returns a plain object, and Drash does not serialize it. Pass it to whichever YAML library your runtime already has:

spec.ts
import { stringify } from "jsr:@std/yaml"; await Deno.writeTextFile("openapi.yaml", stringify(document));

Exports

ExportKindWhat it is
OpenAPIv3decoratorAttaches an Operation Object to a resource’s HTTP method
buildPathsObjectfunctionTurns annotated resources into the paths member of a document
getOperationfunctionReads back the Operation Object one method was given
getOperationsfunctionReads back every description on a resource, keyed by HTTP method name

Twenty object types are exported alongside them, listed under Types.

Types

Every OAS v3 object this module accepts is exported as a type, so you can build an operation in a variable and still be checked:

import type { OperationObject, ParameterObject, PathsObject, ResponsesObject, SchemaObject, } from "@drashland/drash/modules/openapiv3.js"; const getUser: OperationObject = { summary: "Get a user", responses: { "200": { description: "The user" } }, };

The full set: CallbackObject, EncodingObject, ExampleObject, ExternalDocumentationObject, HeaderObject, LinkObject, MediaTypeObject, OperationObject, ParameterObject, PathItemObject, PathsObject, ReferenceObject, RequestBodyObject, ResourceClass, ResourceLike, ResourceMethod, ResponseObject, ResponsesObject, SchemaObject, SecurityRequirementObject, and ServerObject.

Last updated on