Chromia
Start Building

14 / 26Part 3: Checking and validating inputsBeginner

Return structured results from queries

Queries often need to return data assembled from more than one entity, such as a book together with its reviews. You can shape that result with a struct, so the client receives a single, well-defined object instead of loose values.

You will define a book_review_dto struct that holds both the book details and the review details, and then change the query so it returns that struct.

Define the struct

Data structures like this belong in src/main/entities.rell. The new book_review_dto struct carries the book information alongside the review fields.

Add the following code to src/main/entities.rell:

src/main/entities.rell
struct book_review_dto {  book: struct<book>;  reviewer_name: text;  review: text;  rating: integer;}

A field of type struct<book> holds every field of the referenced book entity. Using it in an expression causes an implicit join that loads those fields.

Update the query

Now change get_all_reviews_for_book so it returns book_review_dto values. Each result then contains the book and the review together.

Replace the query in src/main/queries.rell with this version:

src/main/queries.rell
query get_all_reviews_for_book(isbn: text) {  require(book @? { .isbn == isbn }, "Book with isbn %s not found".format(isbn));  val reviews = book_review @* { .book.isbn == isbn } (    book_review_dto(      book = .book.to_struct(),      .reviewer_name,      .review,      .rating    )  );  return reviews;}

Explanation

  1. Struct definition: book_review_dto groups the book and review details into one value, so related data travels as a unit.

  2. Updated query:

    • require verifies that a book with the given ISBN exists.
    • book_review @* { .book.isbn == isbn } selects every review for that book.
    • The struct's book attribute is filled with book_review.book.to_struct(), which turns the entity reference into a struct value. This is what causes the implicit join that loads all fields of the referenced book entity.

Testing the update

Verify the change with the following steps:

  1. Update the node:

    With a Chromia node already running, push the latest version of your dapp to it:

    shell
    chr node update

    Otherwise, start the node with:

    shell
    chr node start
  2. Run the query:

    Call the query from the Chromia CLI:

    shell
    chr query get_all_reviews_for_book "isbn=ISBN1234"

    You should see output similar to this:

    json
    [  {    "book": {      "author": "George Orwell",      "isbn": "ISBN1234",      "title": "1984"    },    "rating": 5,    "review": "It was a great book",    "reviewer_name": "Alice"  }]
Written for this site from Chromia’s public course. Code samples are the course’s own.