QueryOn

View as Markdown

QueryOn

QueryOn<EntryType> is an entry query typed to a model of your own. Use it to filter and sort entries by the cases of your model's FieldKeys, so the compiler catches a misspelled field key.

QueryOn is a subclass of Query. It has every method of Query, BaseQuery and EntryQueryable, and adds the three typed methods in the Method Index below.

Instance State

You never create a QueryOn with an initializer, because its initializer is internal. Call query(_:) on an entry and pass your model type:

  • Call stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self) to query all entries of the content type.
  • Call query(_:) on an entry with a UID to get a query that matches only that entry.

EntryType must adopt EntryDecodable. The Entry class page has an example model.

Class-Level Notes

Typed keys.

  • The typed methods take a case of EntryType.FieldKeys and send its raw value, such as created_at for .createdAt.
  • A case that is not in FieldKeys does not compile. Add every field you filter or sort on to FieldKeys.

Chain order.

  • The methods that Query declares, such as search(for:), tags(for:), where(valueAtKey:_:), where(referenceAtKeyPath:_:) and operator(_:), return Query.
    • After one of them, the typed methods of QueryOn no longer compile in the chain.
  • The methods of BaseQuery and EntryQueryable, such as limit(to:) and locale(_:), return Self and keep the QueryOn type.
  • Call the typed methods first, then the methods of Query.

The find type.

  • QueryOn does not set the model type of find(_:). Name it in the completion handler, as Result<ContentstackResponse<Product>, Error>, or in the async variable annotation.

Properties.

  • QueryOn has the properties of Query (headers, stack, parameters, queryParameter and cachePolicy), and takes its cachePolicy from the content type. See the Query class page.

Method Index

Filter and sort with typed keys. Available on any QueryOn from query(_:), before a method that returns Query.

Method NameReturnsDescription
where(queryableCodingKey:_:)The same query, for chaining.Filters entries on a typed field key.
orderByAscending(propertyName:)The same query, for chaining.Sorts entries by a typed field key, lowest first.
orderByDecending(propertyName:)The same query, for chaining.Sorts entries by a typed field key, highest first.

Inherited methods. Available on any QueryOn. QueryOn also has the methods of Query, BaseQuery, such as find(_:) and limit(to:), and EntryQueryable, such as locale(_:) and include(params:).

Class-Level Snippet

The snippet below finds the ten cheapest products above a price, in French, and decodes them into a Product model.

import ContentstackSwift
import Foundation

class Product: EntryDecodable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self)
    .where(queryableCodingKey: .price, .isGreaterThan(100))
    .orderByAscending(propertyName: .price)
    .locale("fr-fr")
    .limit(to: 10)
    .find { (result: Result<ContentstackResponse<Product>, Error>, response: ResponseType) in
        switch result {
        case .success(let products):
            for product in products.items {
                print(product.title, product.price ?? 0)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Methods

Each method of the QueryOn class has its own section below, with its parameters, validation rules, behavior, and examples.

orderByAscending(propertyName:)

orderByAscending(propertyName:) sorts the entries in ascending order of a field key of your model.

NameTypeDescription
propertyName (required)EntryType.FieldKeys

Field key of your model to sort by.

Default: Not applicable

Returns: QueryOn<EntryType>. The same query, for chaining.

Validation

  • A key that is not a case of EntryType.FieldKeys does not compile.
  • There is no other client-side validation.
  • Errors that do occur come from the find(_:) call that follows, not from orderByAscending(propertyName:).

Additional Resource Refer to Delivery API Errors for the full error code list.

Behavior

  • Client-side only. orderByAscending(propertyName:) writes the raw value of the key to the asc key of parameters and makes no request.
  • find(_:) sends it as the asc query parameter. The API returns the entries with the lowest value first. See Order by asc.
  • A second call replaces the sort key. The method sorts on one field.
  • orderByDecending(propertyName:) writes the separate desc parameter, so calling both sends both parameters.
  • Query has an orderByAscending(propertyName:) that takes EntryModel.FieldKeys. On a QueryOn, the compiler picks this method for the cases of your model.

Example

Sort products by price, lowest first

import ContentstackSwift
import Foundation

class Product: EntryDecodable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self)
    .orderByAscending(propertyName: .price)
    .limit(to: 20)
    .find { (result: Result<ContentstackResponse<Product>, Error>, response: ResponseType) in
        switch result {
        case .success(let products):
            for product in products.items {
                print(product.title, product.price ?? 0)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

orderByDecending(propertyName:)

orderByDecending(propertyName:) sorts the entries in descending order of a field key of your model.

NameTypeDescription
propertyName (required)EntryType.FieldKeys

Field key of your model to sort by.

Default: Not applicable

Returns: QueryOn<EntryType>. The same query, for chaining.

Validation

  • A key that is not a case of EntryType.FieldKeys does not compile.
  • There is no other client-side validation.
  • Errors that do occur come from the find(_:) call that follows, not from orderByDecending(propertyName:).

Additional Resource Refer to Delivery API Errors for the full error code list.

Behavior

  • Client-side only. orderByDecending(propertyName:) writes the raw value of the key to the desc key of parameters and makes no request.
  • find(_:) sends it as the desc query parameter. The API returns the entries with the highest value first. See Order by desc.
  • A second call replaces the sort key. The method sorts on one field.
  • orderByAscending(propertyName:) writes the separate asc parameter, so calling both sends both parameters.
  • The SDK spells the method name orderByDecending, without the "s" of "descending". Use that spelling in code.
  • Query has an orderByDecending(propertyName:) that takes EntryModel.FieldKeys. On a QueryOn, the compiler picks this method for the cases of your model.

Example

Sort products by last update, newest first

import ContentstackSwift
import Foundation

class Product: EntryDecodable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self)
    .orderByDecending(propertyName: .updatedAt)
    .limit(to: 20)
    .find { (result: Result<ContentstackResponse<Product>, Error>, response: ResponseType) in
        switch result {
        case .success(let products):
            for product in products.items {
                print(product.title, product.price ?? 0)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

where(queryableCodingKey:_:)

where(queryableCodingKey:_:) filters the entries on a field key of your model.

NameTypeDescription
queryableCodingKey (required)EntryType.FieldKeys

Field key of your model to filter on.

Default: Not applicable
operation (required)Query.Operation

Condition the field value must meet.

Default: Not applicable

Returns: QueryOn<EntryType>. The same query, for chaining.

Validation

  • A key that is not a case of EntryType.FieldKeys does not compile.
  • There is no other client-side validation.
  • Errors that do occur come from the find(_:) call that follows, not from where(queryableCodingKey:_:).

Additional Resource Refer to Delivery API Errors for the full error code list.

Behavior

  • Client-side only. where(queryableCodingKey:_:) stores the condition under the raw value of the key in queryParameter and makes no request.
  • find(_:) sends every stored condition as one JSON object in the query parameter. See the Equals Operator and the other operators in the API reference.
  • A second call with the same key replaces the condition on that key. Calls with other keys add their own conditions.
  • The Query class page lists the Query.Operation cases, such as .equals(_:), .isGreaterThan(_:) and .includes(_:).
  • where(queryableCodingKey:_:) returns QueryOn<EntryType>, so the typed methods stay available after it.

Example

Find products above a price

import ContentstackSwift
import Foundation

class Product: EntryDecodable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self)
    .where(queryableCodingKey: .price, .isGreaterThan(100))
    .find { (result: Result<ContentstackResponse<Product>, Error>, response: ResponseType) in
        switch result {
        case .success(let products):
            for product in products.items {
                print(product.title, product.price ?? 0)
            }
        case .failure(let error):
            if let apiError = error as? APIError {
                print("Error \(apiError.errorCode): \(apiError.errorMessage)")
            } else {
                print(error)
            }
        }
    }

Combine conditions on two keys

import ContentstackSwift
import Foundation

class Product: EntryDecodable {
    enum FieldKeys: String, CodingKey {
        case title, uid, locale, price
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case createdBy = "created_by"
        case updatedBy = "updated_by"
    }

    var title: String
    var uid: String
    var locale: String
    var createdAt: Date?
    var updatedAt: Date?
    var createdBy: String?
    var updatedBy: String?
    var price: Double?

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: FieldKeys.self)
        title = try container.decode(String.self, forKey: .title)
        uid = try container.decode(String.self, forKey: .uid)
        locale = try container.decode(String.self, forKey: .locale)
        createdAt = try? container.decode(Date.self, forKey: .createdAt)
        updatedAt = try? container.decode(Date.self, forKey: .updatedAt)
        createdBy = try? container.decode(String.self, forKey: .createdBy)
        updatedBy = try? container.decode(String.self, forKey: .updatedBy)
        price = try? container.decode(Double.self, forKey: .price)
    }
}

let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query(Product.self)
    .where(queryableCodingKey: .price, .isLessThanOrEqual(50))
    .where(queryableCodingKey: .title, .matches("^Summer"))
    .find { (result: Result<ContentstackResponse<Product>, Error>, response: ResponseType) in
        guard case .success(let products) = result else { return }
        print(products.items.map { $0.title })
    }