# List posts
To list created posts you use the
blogd query blog list-post and
blogd query blog get-post commands. The
get-post subcommands haven’t been defined yet, so let’s do it now. Query commands (opens new window) from the CLI are handled by
First we define our proto files, in
# Add the Query Proto File
In our proto file you define the structure of the API endpoint, as well as your request and response structure of the post.
# Edit the Query Functions in the CLI
GetQueryCmd is used for creating a list of
query subcommands, it should already be defined. Edit the function to add
CmdShowPost as a subcommand:
CmdListPost in a new
# Add the Query Post to the CLI
CmdShowPost run an ABCI (opens new window) query to fetch the data, unmarshals it back form binary to JSON and returns it to the console. ABCI is an interface between your app and Tendermint (a program responsible for replicating the state across machines). ABCI queries look like paths on a hierarchical filesystem. In our case, the query is
custom/blog/list-post. Before you continue, you need to define
# Add the Two Query Commands to the Types
QueryListPost in a new file
blog/types/query.go that will be used later on to dispatch query requests:
# Add the Query Functions to the Keeper
NewQuerier acts as a dispatcher for query functions, it should already be defined. Modify the switch statement to include
listPost. Create the
# Add the Query Post Functions to the Keeper
Create a new file
query_post.go in the
Make sure to add the codec to the previous import and add the
getPost function in a new file called
query_post.go in our keeper.
In the keeper you also define the grpc of the queryPost function.
# Add GRPC functionality
# Add GRPC to the Module Handler
You add the grpc query handler to your module.
Make sure to import
context and add the
Search for the
RegisterGRPCGatewayRoutes function and add the
This function uses a prefix iterator to loop through all the keys with a given prefix (in our case
"Post-value-"). You get values by key with
store.Get and appending them to
postList. Finally, unmarshal bytes back to JSON and return the result to the console.
Now, you can see how it works. Run the following command to recompile your app, clear the data and relaunch the chain:
After the app has launched, open a different terminal window and create a post:
And confirm the transaction with (y).
Now run the query to see the post:
That’s a newly created post along with your address and a unique ID. Try creating more posts and see the output.
You can also make ABCI (opens new window) queries from the browser:
The result of this query is a base64 encoded string inside
# Known Errors
null is actually not an error, but might be a bit confusing. If you've added a post and immediately issued
list-post subcommand, you may get a
null. This happens because it takes several seconds to process the block. After a couple of seconds you should be able to see output of