With every blog post linked together, we can return all of them by referencing only the CID of the last. This kind of traversal could be used to create an overview page that lists all blog posts chronologically.
The prev
field contains a link to the previous blog post. You can use that CID and the ipfs.dag.get
API to get the previous blog, and then use its prev
field to get the one before that. A perfect use case for a while loop!
Note that the ipfs.dag.get()
API returns an object with a value
attribute which is the node you want and contains the original fields you saved. For example, we could find the author of the post about dogs like so:
const dogPostAuthor = (await ipfs.dag.get(dogPostCid)).value.author
Notice the parentheses used around await ipfs.dag.get(dogPostCid)
above, since the async function needs to complete before the CID object with a property of value
is available. When you're using this code in practice, it's important not to make too many async calls that will create lag time.
Fill in the body of the traversePosts
function. It takes the CID object of the most recent blog post as input. Use that to get the object from IPFS and follow the prev
links. The return value of the function should be an array with the CID objects of all nodes (including the input CID), starting with the most recent post and ending with the oldest post.
Hint: How do you know when you're out of links? Try using a while
loop and checking for the presence of a prev
field in the current object. If it exists, you're not done yet, and you'll need to reset a variable and run the loop again. You'll need to use the array push
method to add the relevant CIDs to your array as you go. As noted above, be careful to minimize the number of async calls that could create lag time, and remember that value
doesn't exist until after your ipfs.dag.get
function has returned a result. (See the last example above.)
Please do not edit the run
function, only the traversePosts
function.