0

I tried to read a list of posts using the code below

struct posts {

  bytes32 postTag;
  string post;
  address[] acceptedBy;
  uint8[] voteCount;

}

mapping(address => posts) totaluserPosts;

I tried to read all the posts in different ways but couldn't find a way to do.

Is it possible to read all the posts through one request?

1
  • Are you trying to return an array of the struct posts?
    – vhie
    Oct 30, 2018 at 1:42

1 Answer 1

0

The short answer is you have to create a function because the "free" getter you receive via the public mapping doesn't do this.

A better answer is to reconsider the need for the bulk data dump. I will usually suffice if you emit events each time something is inserted into this structure and that means software clients should already be informed about this information. Ergo, why ask for it again given that doing so is gas-intensive and not especially fast. A more complete description of this thinking: https://blog.b9lab.com/the-joy-of-minimalism-in-smart-contract-design-2303010c8b09

Suggestion. Naming conventions:

struct PostStruct {

  bytes32 postTag;
  string post;
  address[] acceptedBy;
  uint8[] voteCount;

}

mapping(address => posts) postStructs;

Custom function examples:

function getPostAddressCount(address post, uint row) public returns(uint count) {
  return postStructs[post].address.length;
}

function getPostAcceptedBy(address post) public returns(address[] acceptedBy) {
  return postStructs[post].acceptedBy;
}

Since the cost of the above function increases with scale to the point of being unworkable, it is a good idea to include a fixed-cost alternative:

function getPostAcceptedByByRow(address post, uint row) public returns(address acceptedBy) {
  return postStructs[post].acceptedBy[row];
}

Hope it helps.

2
  • can you explain what you meant by mapping (address => posts) postStructs? @Rob Hitchens B9lab
    – Girish
    Oct 30, 2018 at 2:38
  • Corrected it for consistent renaming. Oct 30, 2018 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.