Adding structured results from queries
In this section, we'll learn how to structure the results from queries in Chromia. This approach can be beneficial when you need to fetch complex data, such as combining book information with associated reviews.
To achieve this, we'll create a book_review_dto
struct to encapsulate the book details and the review information.
We'll then update our query to return this structured data.
Define the struct
We will define a new struct, book_review_dto
, which will contain the book information and review details. This struct
should be added to the src/main/entities.rell
file, which is appropriate for defining such data structures.
Open the src/main/entities.rell
file and add the following code:
struct book_review_dto {
book: struct<book>;
reviewer_name: text;
review: text;
rating: integer;
}
Update the query
Next, we'll modify the get_all_reviews_for_book
query to use the book_review_dto
struct. This will allow us to
include both book and review information in a single query result.
Open the src/main/queries.rell
file and update the query as follows:
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;
}