API revisions

Changing a field

Rename a field or change its type, and declare what it was for older clients with was().

Edit the field to its new shape, then add ->was($revision, name: …, schema: …, down: …): what the field was up to $revision included. Always write was(<the revision that was the newest until now>).

// Initial → Labels → UsersReplaceTeachers (head)
'display_name' => $this->string('name')
    ->was(ApiRevision::Labels, name: 'label')
    ->was(ApiRevision::Initial, name: 'name'),
ClientField rendered
head, UsersReplaceTeachersdisplay_name
Labelslabel
Initialname
  • The changes chain from the head down to the revision of the client, in the order of the revisions (never of the calls). Each was() says what differs from the next newer shape; an argument left out keeps it.
  • Never an if on the revision for a change of shape.

Changing the type

schema: is the type the field had: a descriptor without source, since the model has one version. The value is read once, as the head reads it, then converted down: by the base when it knows the conversion (an integer to a string, a date and time to a date…), otherwise by down:, a closure receiving the value of the newer shape and the model.

'price' => $this->struct([
    'amount' => $this->integer('price_cents'),
    'currency' => $this->string(),
])
    // Labels: integer cents
    ->was(
        ApiRevision::Labels,
        schema: $this->integer(),
        down: fn(array $price) => $price['amount'],
    )
    // Initial: still integer cents, under another name
    ->was(ApiRevision::Initial, name: 'amount'),

php artisan jsonapi:check reports a conversion that is missing (conversion-missing).

Relationships

A relationship declares its old name, include path and fields, its old related resource and cardinality, with schema: holding the relationship as it was. No value is converted.

'instructor' => $this->one(UserResource::class)
    ->was(
        ApiRevision::Labels,
        name: 'teacher',
        schema: $this->one(TeacherResource::class),
    ),

What follows the revision

  • The conditions (->when(), ->whenHas()…) are those of the head field. whenInFields() and whenInIncludes() follow the names of the revision, which the client writes.
  • The links of #[JsonApiRoutes] follow the relationships of the revision and their names: an old client gets posts.relationships.writer, never a relationship its revision does not have.
  • The links of toLinks() hold no history: compute one that changes with ApiRevision::current().