In this section you will learn how users query messages on the forum application.
The Query
method is used to query the application state for specific information. It allows clients to request data
from the application without submitting a transaction.
The Query
method is responsible for retrieving data from the application state based on the provided query parameters.
The query parameters can be specified in the QueryRequest
object, which typically includes information such as the
query path and the query data.
The application is expected to interpret the query parameters and return the corresponding data in a QueryResponse
object.
The response may include the requested data, error codes, or any other relevant information based on the application’s implementation.
The Query
method is usually particularly useful for retrieving specific information from the application, such as
account balances, transaction history, or any other data stored in the application’s state.
Following is the code for the Query
function:
// Query the application state for specific information.
func (app *ForumApp) Query(_ context.Context, query *abci.QueryRequest) (*abci.QueryResponse, error) {
app.logger.Info("Executing Application Query")
resp := abci.QueryResponse{Key: query.Data}
// Parse sender from query data
sender := string(query.Data)
if sender == "history" {
messages, err := model.FetchHistory(app.state.DB)
if err != nil {
return nil, err
}
resp.Log = messages
resp.Value = []byte(messages)
return &resp, nil
}
// Retrieve all message sent by the sender
messages, err := model.GetMessagesBySender(app.state.DB, sender)
if err != nil {
return nil, err
}
// Convert the messages to JSON and return as query result
resultBytes, err := json.Marshal(messages)
if err != nil {
return nil, err
}
resp.Log = string(resultBytes)
resp.Value = resultBytes
return &resp, nil
}
Explanation of code:
Query
function queries the application state. It takes a context and a query as input and returns a response or an error.
If the query data is equal to “history”, it fetches the history of messages from the application’s state database and returns it as a response. Otherwise, it retrieves all messages sent by the sender specified in the query data, converts them to JSON, and returns them as the query result.
Tip: The function Query
can still fetch previous messages from a sender before it was banned. You can change this to
delete all messages from a banned sender.
In the next session, you will learn about different models and functions and how they are used in the Forum Application.