Skip to content

Improving model serialization process by allowing fields to pick or omit

Choose a tag to compare

@thetutlage thetutlage released this 01 May 10:03

The serialization process accepts a tree of fields to pick and omit for the model and its relationships. Example:

const user = await User.find(1)
user.serialize({
  fields: ['username', 'email', 'id'],
})

// Verbose mode
user.serialize({
  fields: {
    pick: ['username', 'email', 'id'],
    omit: ['id']
  },
})

When pick and omit both have the same set of properties, the omit will win.

Relationships

Quite often you would want to also cherry pick fields for relationships as well.

user.serialize({
  fields: {
    pick: ['username', 'email', 'id'],
    omit: ['id']
  },
  relations: {
    posts: {
      fields: ['title', 'body', 'published_at']
    }
  }
})

Feels verbose?

Well, you will never type these fields to pick or omit manually. Usually, you will be following an API standard like JSONAPI, which allows the consumer of your API to specify the fields. There we will be a preprocessor in between the model.serialize the user defined query string options. That preprocessor will convert the query string to this tree.

Commits

  • improvement: adding support to pick and omit fields during serialize process d3d4f92

v8.0.5...v8.1.0