【发布时间】:2022-01-11 08:49:02
【问题描述】:
我只是在学习稳固性。以前,solidity 不允许我们返回结构数组。但是我们可以在较新的版本中做到这一点。您更喜欢以下哪种架构来获取用户发布的帖子列表? (我想在客户端显示列表)
合同样本:
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 ?
}
方法一:
/// @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;
}
方法二:
Just return the post IDs and then call the posts on the client side.
【问题讨论】:
标签: blockchain ethereum solidity smartcontracts truffle