Decorators

Contract Decorators

Declare TypeScript API contracts with AxilJS: request/response/error schemas, accepted and produced content types, pagination and deprecation metadata.

7 min readUpdated DocumentationEdit this page
On this page12

AxilJS contract decorators describe the public surface of an API operation: what it accepts, what it returns, which errors it can produce, how collections are paged, and whether the operation is on its way out.

They record that contract as semantic metadata next to the method. Validation, OpenAPI and SDK generation, Studio, or your own tooling can read the same declaration instead of each keeping a separate copy of the contract.

The contract decorators are:

  • @tContract
  • @tConsumes
  • @tProduces
  • @tPaginated
  • @tDeprecated

All five belong to the Contract category (axil decorator list --category Contract).

@tContract

Declares a full request/response contract for a method.

TypeScript
TS
1import { tHttp, tContract } from '@axiljs/decorator'
2
3class UserResponse {}
4class CreateUserRequest {}
5class ValidationProblem {}
6class ConflictProblem {}
7
8class UserApi {
9  @tHttp({ method: 'GET', path: '/users/:id' })
10  @tContract({ response: UserResponse })
11  async getUser(id: string) {}
12
13  @tHttp({ method: 'POST', path: '/users' })
14  @tContract({
15    request: CreateUserRequest,
16    response: UserResponse,
17    errors: {
18      409: ConflictProblem,
19      422: ValidationProblem,
20    },
21  })
22  async createUser(body: CreateUserRequest) {}
23}

tContract(options) is a method decorator. The options object is required and is stored as-is under the tContract key.

Options

OptionTypeDescription
requestunknownRequest body contract (a class, schema or any descriptor)
responseunknownSuccessful response contract
errorsRecord<number, unknown>Error contracts keyed by HTTP status code

Every option is optional and has no default. The fields are typed unknown, so the decorator does not care whether you pass a class, a @axiljs/validation schema or a plain descriptor object; the consumer that reads the metadata decides how to interpret it.

When to use: on public API endpoints with published contracts. Explicit contracts are what drive validation, OpenAPI, SDK and Studio tooling.

Composes with: tHttp, tConsumes, tProduces, tPaginated.

@tConsumes

Declares the request content types an endpoint accepts.

TypeScript
TS
1import { tHttp, tConsumes } from '@axiljs/decorator'
2
3class UploadApi {
4  @tHttp({ method: 'POST', path: '/users' })
5  @tConsumes('application/json')
6  async createUser(body: unknown) {}
7
8  @tHttp({ method: 'POST', path: '/avatars' })
9  @tConsumes('image/png', 'image/jpeg', 'image/webp')
10  async uploadAvatar(body: Buffer) {}
11}

tConsumes(...contentTypes: string[]) takes MIME types as rest arguments, not as an array. It records { contentTypes } under the tConsumes key. Calling it with no arguments records an empty list.

When to use: on endpoints with a restricted content-type surface, where content negotiation is part of the published contract.

Composes with: tHttp, tContract.

@tProduces

Declares the content type an endpoint returns.

TypeScript
TS
1import { tHttp, tProduces } from '@axiljs/decorator'
2
3class ReportApi {
4  @tHttp({ method: 'GET', path: '/reports/:id/export' })
5  @tProduces({ contentType: 'text/csv', charset: 'utf-8' })
6  async exportCsv(id: string) {}
7}

tProduces(options) stores the options object as-is under the tProduces key.

Options

OptionTypeDescription
contentTypestringResponse MIME type (required)
charsetstringOptional character set, e.g. 'utf-8'

There is no default charset.

When to use: on endpoints returning non-default content types (CSV, PDF, images, plain text). JSON endpoints that use the standard @axiljs/core response envelope usually do not need it.

Composes with: tHttp, tContract.

@tPaginated

Marks an endpoint as returning a paginated collection envelope.

TypeScript
TS
1import { tHttp, tPaginated } from '@axiljs/decorator'
2
3class User {}
4
5class UserApi {
6  @tHttp({ method: 'GET', path: '/users' })
7  @tPaginated({ item: User, strategy: 'offset', defaultLimit: 20, maxLimit: 100 })
8  async listUsers() {}
9
10  @tHttp({ method: 'GET', path: '/events' })
11  @tPaginated({ strategy: 'cursor' })
12  async listEvents() {}
13}

tPaginated(options = {}) can be called with no arguments; it then records an empty object.

Options

OptionTypeDescription
itemunknownContract of a single item in the page
strategy'offset' | 'cursor' | 'keyset'Pagination strategy
defaultLimitnumberPage size when the client does not send one
maxLimitnumberUpper bound on the client-requested page size

None of these options has a default in the decorator; only the values you pass are recorded. The decorator does not paginate anything itself. To actually send a paginated envelope from an @axiljs/core handler, use res.paginated(...).

When to use: on any list endpoint that returns bounded pages.

Composes with: tHttp, tContract.

@tDeprecated

Marks an endpoint, method or whole class as deprecated.

TypeScript
TS
1import { tHttp, tDeprecated } from '@axiljs/decorator'
2
3class UsersV2Api {
4  @tHttp({ method: 'GET', path: '/v2/users' })
5  @tDeprecated({
6    since: '2.0',
7    removeAfter: '3.0',
8    replacement: '/v3/users',
9    message: 'Use /v3/users, which supports cursor pagination.',
10  })
11  async listUsers() {}
12}
13
14@tDeprecated({ since: '2.5', replacement: 'BillingV3Api' })
15class BillingV2Api {}

tDeprecated(options = {}) targets methods and classes. On a method the options are stored as method metadata; on a class they are stored as class metadata on the constructor.

Options

OptionTypeDescription
sincestringVersion in which the operation was deprecated
removeAfterstringVersion after which it may be removed
replacementstringPath, method or class to use instead
messagestringFree-form deprecation notice

All options are optional and have no defaults.

When to use: on endpoints scheduled for removal or replacement.

Composes with: tHttp.

Composing Contract Semantics

Contract decorators are designed to sit next to tHttp and describe one operation completely.

TypeScript
TS
1import {
2  tHttp,
3  tContract,
4  tConsumes,
5  tProduces,
6  tPaginated,
7} from '@axiljs/decorator'
8
9class Order {}
10class OrderQuery {}
11class BadQuery {}
12
13class OrderApi {
14  @tHttp({ method: 'POST', path: '/orders/search' })
15  @tConsumes('application/json')
16  @tProduces({ contentType: 'application/json', charset: 'utf-8' })
17  @tContract({
18    request: OrderQuery,
19    errors: { 400: BadQuery },
20  })
21  @tPaginated({ item: Order, strategy: 'keyset', defaultLimit: 50, maxLimit: 200 })
22  async searchOrders(query: OrderQuery) {}
23}

The resulting metadata describes:

  • The HTTP method and path.
  • The single accepted request content type.
  • The response content type and charset.
  • The request body contract and the error returned for a bad query.
  • A keyset-paginated collection of Order items with bounded page size.

None of the contract decorators declare a conflictsWith relationship, so axil decorator check will not flag any combination of them.

Note

Contract decorators only record metadata. Their catalog entries list @axiljs/core, @axiljs/studio, an OpenAPI generator, an SDK generator and (for tDeprecated) a runtime warning as intended consumers, but no AxilJS package reads this metadata today: @axiljs/runtime executes only tAudit, tRetry and tTimeout and applies tRedact / tSensitive redaction. tConsumes does not reject other content types and tDeprecated does not log a warning. Read the declarations yourself with getMetadata(), or inspect them with the axil decorator commands. See Runtime.

Reading Contract Metadata

Method-level metadata is stored on the class prototype; class-level metadata (tDeprecated on a class) is stored on the constructor.

TypeScript
TS
1import { getMetadata, type TContractOptions, type TDeprecatedOptions } from '@axiljs/decorator'
2
3const contract = getMetadata<TContractOptions>('tContract', UserApi.prototype, 'createUser')
4// { request: CreateUserRequest, response: UserResponse, errors: { 409: ..., 422: ... } }
5
6const consumes = getMetadata<{ contentTypes: string[] }>('tConsumes', UploadApi.prototype, 'uploadAvatar')
7// { contentTypes: ['image/png', 'image/jpeg', 'image/webp'] }
8
9const classDeprecation = getMetadata<TDeprecatedOptions>('tDeprecated', BillingV2Api)
10// { since: '2.5', replacement: 'BillingV3Api' }

The exported option types are TContractOptions, TProducesOptions, TPaginatedOptions and TDeprecatedOptions.

Contract Decorator Reference

DecoratorTargetsRecordsPurpose
@tContractmethodTContractOptionsBinds request, response and error contracts
@tConsumesmethod{ contentTypes: string[] }Lists accepted request MIME types
@tProducesmethodTProducesOptionsDeclares the response MIME type
@tPaginatedmethodTPaginatedOptionsMarks a paginated collection response
@tDeprecatedmethod, classTDeprecatedOptionsMarks an operation as deprecated

Design Principle

Contract decorators declare the API contract once, at the operation.

For example:

TypeScript
TS
@tContract({ response: UserResponse })
async getUser() {}

does not validate the response or generate documentation by itself. It states what the operation promises, so that validation, documentation, client generation and developer tooling can all derive from the same source instead of drifting apart. See the decorator overview for how metadata is stored and consumed.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY