Skip to content

API Resources ​

Introduction ​

toJSON() on a model returns the table's shape: its columns, minus hidden ones. An API usually wants something else: renamed keys, computed fields, values shown only to some callers, related data nested in a stable format. An API resource is a class that sits between your model and your JSON response and defines that shape explicitly.

ts
import { JsonResource } from '@plinthjs/orm'

A resource wraps any value (usually a model), has one required method, toArray(), and serializes to JSON with the whole result wrapped in a data key. Collections and paginated lists get the same treatment.

The examples use these models and data:

ts
import { Schema, sqliteConnection } from '@plinthjs/database'
import { ConnectionDataSource, Model } from '@plinthjs/orm'
import type { CastType } from '@plinthjs/orm'

const db = sqliteConnection()
Model.connection = db
Model.dataSource = new ConnectionDataSource(db)

const schema = new Schema(db)
await schema.create('users', (table) => {
  table.id()
  table.string('name')
  table.string('email')
  table.boolean('is_admin').default(false)
  table.timestamps()
})
await schema.create('posts', (table) => {
  table.id()
  table.integer('user_id')
  table.string('title')
  table.timestamps()
})

class Post extends Model {
  static override table = 'posts'
  static override fillable = ['title']
}

class User extends Model {
  static override table = 'users'
  static override fillable = ['name', 'email', 'is_admin']
  static override casts: Record<string, CastType> = { is_admin: 'boolean' }
  static override relations = {
    posts: (model: Model) => model.hasMany(Post, 'user_id'),
  }
}

Generating Resources ​

Extend JsonResource and return the shape from toArray(). The wrapped value is available as this.resource, typed by the generic parameter:

ts
class PostResource extends JsonResource<Post> {
  toArray() {
    return {
      id: this.resource.getKey(),
      title: this.resource.getAttribute('title'),
    }
  }
}

A user resource follows the same pattern. It is used in the examples below:

ts
class UserResource extends JsonResource<User> {
  toArray() {
    return {
      id: this.resource.getKey(),
      name: this.resource.getAttribute('name'),
    }
  }
}

Build one with make() (or new). resolve() returns the plain object, and toJSON() returns it wrapped in the data envelope, which is what JSON.stringify uses:

ts
const post = (await Post.find(1))!

PostResource.make(post).resolve() // => { id: 1, title: 'Hello' }
PostResource.make(post).toJSON() // => { data: { id: 1, title: 'Hello' } }
JSON.stringify(PostResource.make(post)) // => '{"data":{"id":1,"title":"Hello"}}'

Because a resource serializes through toJSON(), you can return it from a route handler or pass it to Response.json() directly:

ts
import { Response } from '@plinthjs/http'

Response.json(PostResource.make(post)) // body: {"data":{"id":1,"title":"Hello"}}

See Responses for how handler results become responses.

Resource Collections ​

collection() builds a resource for every item in an array. The result serializes as { data: [...] }:

ts
const users = await User.all()

JSON.stringify(UserResource.collection(users))
// => '{"data":[{"id":1,"name":"Ann"}, ...]}'

UserResource.collection(users).resolveItems() // the bare array, without the envelope

An empty array serializes as {"data":[]}.

Data Wrapping ​

By default the outermost resource is wrapped in data. To change the key or remove the wrapper, override the protected wrapKey() method. Return a string for a different key, or null for no wrapping:

ts
class UnwrappedUser extends UserResource {
  protected override wrapKey(): string | null {
    return null
  }
}

JSON.stringify(UnwrappedUser.make(user)) // => '{"id":1,"name":"Ann"}'

class NamedUser extends UserResource {
  protected override wrapKey(): string | null {
    return 'user'
  }
}
// => {"user":{...}}

To rename the key of a collection, extend ResourceCollection and override wrapKey() the same way:

ts
import { ResourceCollection } from '@plinthjs/orm'

class UserList extends ResourceCollection<UserResource> {
  protected override wrapKey(): string | null {
    return 'users'
  }
}

JSON.stringify(new UserList(models.map((model) => new UserResource(model))))
// => {"users":[...]}

Resources nested inside another resource are never wrapped, so you do not get data inside data.

Conditional Attributes ​

Sometimes an attribute belongs in the output only under some condition. Wrap its value in this.when(condition, value). When the condition is falsy the key is omitted from the output entirely (it is not null or undefined). Here UserResource gains an email that only administrators expose:

ts
class UserResource extends JsonResource<User> {
  toArray() {
    return {
      id: this.resource.getKey(),
      name: this.resource.getAttribute('name'),
      email: this.when(this.resource.getAttribute('is_admin'), this.resource.getAttribute('email')),
    }
  }
}

UserResource.make(admin).resolve() // => { id: 1, name: 'Ann', email: 'ann@example.com' }
UserResource.make(member).resolve() // => { id: 2, name: 'Bob' }

Conditional relationships ​

this.whenLoaded(model, relationName, transform) includes a relation only when it has been loaded onto the model. If it was not loaded, the key is omitted, and no query is run. The transform receives the loaded value, so this is the place to turn related models into nested resources:

Add the relation to UserResource:

ts
class UserResource extends JsonResource<User> {
  toArray() {
    return {
      id: this.resource.getKey(),
      name: this.resource.getAttribute('name'),
      posts: this.whenLoaded(this.resource, 'posts', (posts) =>
        PostResource.collection(posts as Post[]),
      ),
    }
  }
}

const withPosts = (await User.query().with('posts').first())!
UserResource.make(withPosts).resolve()
// => { id: 1, name: 'Ann', posts: [{ id: 1, title: 'Hello' }] }

UserResource.make((await User.find(2))!).resolve()
// => { id: 2, name: 'Bob' }   (posts not loaded, so omitted)

Because the controller decides what to load, the same resource serves a list endpoint (no relations, cheap) and a detail endpoint (with('posts')) without changes.

Nested Resources ​

Return a resource or a resource collection as a value, and it is resolved recursively. Nested items are resolved to plain objects without an envelope:

ts
class TeamResource extends JsonResource<{ id: number; members: User[] }> {
  protected override wrapKey(): string | null {
    return null
  }

  toArray() {
    return {
      id: this.resource.id,
      members: UserResource.collection(this.resource.members),
    }
  }
}

A resource can wrap any value, not only a model. Here the wrapped value is a plain object.

Pagination ​

Pass one of the @plinthjs/database paginators to collection() and you get a PaginatedResourceCollection. It serializes as { data, links, meta }: each page item goes through the resource into data, and the paginator's own pagination keys go into meta. See Pagination.

Paginate a model builder to get a paginator of models:

ts
const paginator = await User.newQuery().orderBy('id').paginate(2, 2)

JSON.stringify(UserResource.collection(paginator))
// => {
//   "data": [{"id":3,"name":"Cy"},{"id":4,"name":"Dee"}],
//   "links": {},
//   "meta": {"total":5,"per_page":2,"current_page":2,"last_page":3,"from":3,"to":4}
// }

The three paginators produce different meta (a paginator that was given a path also reports it as meta.path):

  • LengthAwarePaginator: total, per_page, current_page, last_page, from, to.
  • Paginator (simple): per_page, current_page.
  • CursorPaginator: per_page, next_cursor, prev_cursor.

The links object receives first_page_url, last_page_url, next_page_url and prev_page_url when the paginator was given a path (see Pagination); without a path it is an empty object.

ts
const page = await User.newQuery().orderBy('id').paginate(2, 2, { path: '/users' })

JSON.stringify(UserResource.collection(page))
// => { "data": [...], "links": { "first_page_url": "/users?page=1", "last_page_url": "/users?page=3",
//      "next_page_url": "/users?page=3", "prev_page_url": "/users?page=1" }, "meta": { ..., "path": "/users" } }

TIP

paginate() and simplePaginate() on a model builder (User.paginate(2, 15), User.where(...).paginate()) return paginators of models, so you can pass them straight to collection(). The paginate() helper in @plinthjs/database runs against a table and returns plain rows.

When a paginated collection is nested inside another resource, only the resolved items are used (the same bare array as resolveItems()).

Released under the MIT License.