Solidity - return struct array vs uint array
I'm just learning solidity. Previously, solidity did not allow us to return an array of structs. But we can do it in newer versions. Which of the following architectures do you prefer to get the posts list published by the user? (I want to show the list on the client)
Sample Contract:
contract Post {
// State variables
uint256 private currentIndex = 0;
/// ... another variables
struct PostStruct {
uint256 id;
address user;
string title;
string body;
string thumbnail;
PostStatusEnum status;
bool deleted;
}
PostStruct[] private posts;
mapping(address => uint256[]) postIndexesByUser; // example: 0x01234 => [3, 5, 24, 112, 448]
/// METHOD 1 OR METHOD 2 ?
}
Method 1:
/// @notice This function returns post by user address.
/// @dev We will get _page and _perPage for pagination
function getPostsByUser(
address _user,
uint256 _page,
uint256 _perPage
)
external
view
onlyValidPostPage(_page)
onlyValidPostPerPage(_perPage)
returns (PostStruct[] memory)
{
uint256[] memory allPostIds = postIndexesByUser[_user];
PostStruct[] memory result = new PostStruct[](_perPage);
uint256 index = 0;
require(
_page * _perPage - _perPage < allPostIds.length,
"There is no data to display."
);
for (uint256 i = _perPage * _page - _perPage; i < _perPage * _page; i++) {
if (i < allPostIds.length) {
result[index] = posts[allPostIds[i]];
index++;
}
}
return result;
}
Method 2:
Just return the post IDs and then call the posts on the client side.
Solution 1:
Use method2. Try not to use heavy calculations on the contract code because that will cost you alot of gas fee. Imagine you have 1000's of post and you have to pay for each calculation.