PhoenixAssets.Commands.Definitions (PhoenixAssets v0.1.0)

View Source

DSL for declaring the server mutations that drive generated TypeScript clients.

Reads are shapes; everything that changes state is a command. A host module uses this and declares each mutation with the endpoint that serves it, the request body it accepts, the payload it returns, and — the part that makes the contract worth having — the exact error codes it can answer with:

defmodule MyApp.Assets.Commands do
  use PhoenixAssets.Commands.Definitions

  command :publish_article,
    route: "/api/articles/:id/publish",
    method: :post,
    params: [id: :string],
    body: [note: :string],
    result: "ArticleRow",
    errors: [:already_published, :article_not_found]
end

The generated client returns a discriminated result, so a caller cannot read the payload without handling failure, and an error code the server stops sending becomes a TypeScript error at every call site that still matches on it.

Options per command/2:

  • :route (required) -- the Phoenix route, :placeholders allowed.
  • :method -- :post (default), :put, :patch or :delete.
  • :params -- keyword list of {placeholder, :string | :integer}; must match the route's placeholders exactly. Untyped placeholders default to string | number.

  • :body -- a TypeScript type name, or a keyword list of {field, type} rendered as an interface. A field type is a scalar (:string, :map, ...) or another TypeScript type name. Field names are emitted as exact JSON keys and quoted when TypeScript requires it.
  • :result -- the TypeScript type of the success payload, or a keyword list of {key, type} when the endpoint wraps it (result: [job: "VideoRenderJobRow"] describes {"job": {...}}). Omit for a command that returns nothing meaningful.
  • :errors -- the error codes the endpoint answers with. Any other code the server returns degrades to "unknown_error" at runtime.

Declarations are validated at compile time: a missing :route, an unknown option, a glob segment, a :params list that does not match the route, an unsupported body field type or a duplicate name is a compile error.

use PhoenixAssets.Commands.Definitions

Using this module imports command/2 and defines __phoenix_assets_commands__/0 with the validated declarations.

Summary

Functions

Declares a command: route:, method:, params:, body:, result:, errors:.

The HTTP methods a command may declare.

Functions

command(name, opts)

(macro)

Declares a command: route:, method:, params:, body:, result:, errors:.

methods()

@spec methods() :: [atom()]

The HTTP methods a command may declare.