Previous and next document
I'm wondering how best to add information about the previous and next post. I wanted to do it in the transform() function, but TypeScript throws errors when I try to return any retrieved document.
I have this code:
transform: async (document, context) => {
const mdx = await compileMDX(context, document);
const previous = context.documents(docs).find(() => {
// find previous
return true;
});
return {
...document,
mdx,
previous,
};
},
The error is: transform implicitly has return type any because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
I'm not sure if it's a good idea to do this in the transform() function. Any ideas on how to do it properly to add information about the previous and next post?
Hi @Kuzry, it is not possible to access the documents of a collection within the transform function of the same collection.
The simplest thing that comes to my mind to implement previous/next is to do this in your application code. First, you have to sort your collection, then you can search the index of the current document and calculate the next and the previous document.
const index = sortedDocs.findIndex((doc) => doc._meta.path === currentDoc._meta.path);
const previous = sortedDocs.at(index - 1);
const next = sortedDocs.at(index + 1);