Querying content

A pages instance is used to query the data stored in the CMS. To create an instance use the initPages function.

import {initPages} from '@alinea/generated/pages'

// The initPages method also accepts a previewToken to query
// drafts while previewing, see the next chapter on how to obtain one
const pages = initPages()

Retrieving a page

A single page can be fetched using the first method. Criteria can be passed to filter entries.

// Fetch the first page where field equals the string 'value'
const page = await pages.first(page => page.field.is('value'))

Retrieving multiple pages

Multiple pages can be fetched using the where method.

// Fetch all pages where field equals the string 'value'
const pages = await pages.where(page => page.field.is('value'))

Limiting results

A result set can be limited using skip and take.

// Skip the first 10 pages and return a maximum of 10
const limited = await pages.skip(10).take(10)

Querying specific pages

To filter pages on specific fields first narrow the search to a type, then use the where method to specify conditions.

import {initPages} from '@alinea/generated/pages'

const old = await pages.whereType('Animal').where(
  animal => animal.age.greater(10)
)
const teenager = await pages.whereType('Human').where(
  human => 
    human.age.greater(10).or(
      human.age.less(20)
    )
)
const applesOrOranges = await pages.whereType('Fruit').where(
  fruit => fruit.title.isIn(['apple', 'orange'])
)

Ordering results

A result set can be ordered by passing one or multiple fields.

const ordered = await pages
  .whereType('NewsItem')
  .orderBy(item => [item.publishDate.desc()])

Group by

Results can be grouped by one or more fields.

const ordered = await pages
  .whereType('NewsItem')
  .orderBy(item => [item.category])

Selecting specific fields

Resulting rows can be narrowed to contain only specific fields.

// Return only titles
const rows = await pages
  .select(page => ({
    title: page.title
  })

Processing fields

It's possible to process field values by passing a function, which can be async.

const row = await pages
  .first()
  .select(page => ({
    title: 
      page.title.process(title => `process title ${title}`)
  })