Skip to content

Fields ​

The examples on this page use the UserModel and PostModel models from Relations.

Choose the exposed fields ​

To expose only some fields of a type, list them in fields:

ts
const graph = r.graph({
  User: r.model(UserModel, {
    fields: {
      id: true,
      name: true,
      posts: true,
    },
  }),
  Post: r.model(PostModel),
})

true resolves the field from the column, relation, or getter of the same name. The graph rejects a query for any field that is not listed, such as a password column that the GraphQL schema declares.

Which fields a type resolves depends on its options:

  • By default, a type without fields resolves every field of the GraphQL type from the column, relation, or getter of the same name.
  • With fields, and without allowAllFields: true, the type resolves only the listed fields.
  • With allowAllFields: true on the type or on the graph, the type resolves every field, and fields only overrides how the listed ones resolve. allowAllFields: false on a type restores its fields list under allowAllFields: true of the graph.
ts
const graph = r.graph({
  User: r.model(UserModel, {
    // Every field, with name overridden.
    allowAllFields: true,
    fields: { name: r.field({ transform: name => name.toUpperCase() }) },
  }),
  Post: r.model(PostModel),
})

Rename a field ​

When the GraphQL field has a different name than the column, map it to the column:

ts
const graph = r.graph({
  Post: r.model(PostModel, {
    fields: {
      id: true,
      body: "text",
    },
  }),
})

To combine the new name with other options, pass the column as tableField of r.field:

ts
body: r.field({ tableField: "text", transform: text => text.trim() })

Compute a field in SQL ​

To compute a field in the database, pass a function that selects it under the name of the GraphQL field:

ts
import { raw } from "objection"

const graph = r.graph({
  Post: r.model(PostModel, {
    fields: {
      id: true,
      text: true,
      upper_text: query => query.select(raw("upper(text) as upper_text")),
    },
  }),
})

The function runs only when the client selects the field.

Post-process a value ​

To change a selected value before the response, pass transform(value, instance, context) to r.field. Combine it with modify, which selects the value instead of the column, to post-process a value computed in SQL:

ts
const graph = r.graph({
  Post: r.model(PostModel, {
    fields: {
      id: true,
      preview: r.field({
        // One character more than the preview shows, to tell whether the text is longer.
        modify: query => query.select(raw("substr(text, 1, 101) as preview")),
        transform: preview => (preview.length > 100 ? preview.slice(0, 100) + "…" : preview),
      }),
    },
  }),
})

transform may return a promise. instance is the object with its other selected columns, and the context property of the third argument holds the GraphQL context.