Models and mappings

A script moves data between services. bbrun uses DRef to say what that data must look like: a model is checked with one statement, and an answer in someone else's shape is turned into yours before the script touches it.

The domain document

Models are written in a DRef domain document, a JSON file. bbrun reads domain.json next to the configuration file, or the file that domain: names in bbrun.yaml.

domain.json
{
  "$schema": "https://dref.dev/schemas/v1/domain.json",
  "name": "order-service",
  "version": "1.1.0",
  "defaults": {
    "fields": {
      "PositiveMoney": { "type": "Number", "rules": [{ "type": "positive" }, { "type": "precision", "param": 2 }] },
      "CurrencyCode": { "type": "String", "rules": [{ "type": "uppercase" }, { "type": "enum", "param": ["USD", "EUR"] }] }
    }
  },
  "models": [
    {
      "name": "PlaceOrderRequest",
      "properties": [
        { "name": "productId", "type": "String", "required": true, "key": true },
        { "name": "quantity", "type": "Number", "required": true, "rules": [{ "type": "positiveInteger" }] }
      ]
    }
  ]
}
  • A model has a name and properties. A property has a type, may be required, and may carry rules.
  • The types are String, Number, Boolean, Date, DateTime, Time, and the field types the document defines itself under defaults.fields, such as CurrencyCode above.
  • A rule marked "warnOnly": true is reported and never fails a check.

The document is DRef's, and so are its words. bbrun adds nothing to it: it hands the file to DRef and asks it to check and to map. bbrun models lists what the document declares:

terminal
$ bbrun models
DRef Domain Models (3):

  • ProductResponse (ENTITY, authority=EXTERNAL, ttl=null)
      - id: String [REQUIRED]
      - name: String [REQUIRED] (1 rules)
      - unitPrice: Number [REQUIRED] (2 rules)
      - currency: String [REQUIRED] (2 rules)

Checking a value

bbrun
validate response.body as OrderResponse          // fails the script, listing the fields

if not (request.body matches PlaceOrderRequest) {    // true or false, to decide with
    status(400)
    return { "code": "INVALID_ORDER" }
}
  • validate value as Model stops the script when the value is not a valid Model, and says which fields are wrong and why.
  • value matches Model is the same check as an expression.

In a test, the document describes the contract of the API under test, and validate checks every answer against it. In an operation, it describes what the service accepts and what it stores, and nothing invalid goes further.

Mapping a provider's answer

The services you call speak their own shape. A catalogue answers sku, label and price_cents; your model has id, name and unitPrice. A mapping says how one becomes the other. It is written on the model it produces, in mapsFrom, so the mapping and the model cannot drift apart:

domain.json
{
  "name": "Product",
  "authority": "external",
  "mapsFrom": [
    {
      "name": "Catalog product",
      "provider": "Catalog Service",
      "fields": [
        { "from": "sku", "to": "id" },
        { "from": "label", "to": "name" },
        { "from": "price_cents", "to": "unitPrice", "transform": [{ "type": "divide", "param": 100 }] },
        { "from": "currency", "to": "currency", "transform": ["upperCase"] }
      ]
    }
  ],
  "properties": [
    { "name": "id", "type": "String", "required": true, "key": true },
    { "name": "name", "type": "String", "required": true },
    { "name": "unitPrice", "type": "PositiveMoney", "required": true },
    { "name": "currency", "type": "CurrencyCode", "required": true }
  ]
}
A field isMeaning
"id"copied under the same name
{ "from": "sku", "to": "id" }renamed
{ "from": ["first", "last"], "to": "name" }several fields, those that are present, joined into one
"transform": […]changed on the way, by the transforms in order

The transforms are DRef's: lowerCase, upperCase, trim, prefix, suffix, stripPrefix, stripSuffix, replace, substring, join, multiply, divide, abs, round, roundTo, toNumber, toString, toBoolean, formatDate, default, constant and custom.

Naming the mapping on a resource

A resource says which mapping its answers go through:

bbrun.yaml
catalogApi:
  baseUrl: "https://catalog.example.com"
  mapping: "Catalog product"

In the script

With the resource bound to its mapping, a declaration with the name of the model does three things in one statement: it maps the answer, validates the result, and keeps it. If the provider sent something that does not make a valid Product, the script fails there.

bbrun
catalogApi.get("/products/${request.path.id}")
Product product = response.body

assert product.unitPrice == 12.5                 // your shape: price_cents / 100
assert response.body.price_cents == 1250         // the provider's answer is still there

A list is mapped element by element:

bbrun
Product[] products = catalogApi.get("/products")

validate and matches on the answer of such a resource map it first, so the check is against your model, not the provider's shape:

bbrun
catalogApi.get("/products/P100")
validate response.body as Product

And map applies any mapping by its name, when you want to say it yourself:

bbrun
map response.body using "Catalog product" as product
validate product as Product

Found at the start, not in production

Mappings are checked when the domain document is read: a transform that does not exist, a parameter of the wrong type, a field without from or the same from twice are reported before any script runs. So is a resource that names a mapping no model declares.

A test of an API needs no mapping: it checks the answers as they are received. Mappings belong to the service that calls a provider.