sdorra / content-collections

Transform your content into type-safe data collections
https://content-collections.dev
MIT License
187 stars 8 forks source link

Sort collection #169

Open n1ckoates opened 4 days ago

n1ckoates commented 4 days ago

Just found out about Content Collections, really enjoy this library!

It'd be cool if we could run some transformation to the entire collection array before it's written to the filesystem. I'm wanting to sort my blog posts by creation date, and I don't see a way to do that without sorting them in every spot I import posts.

API could be something like this:


const posts = defineCollection({
    name: "posts",
    remap: (documents) => {
        // Whatever is returned from this function replaces the array
        return documents.sort((a, b) => b.date.getTime() - a.date.getTime());
    }
});
sdorra commented 4 days ago

This definitely makes sense, but I'm not sure what the API should look like. Can it only change the order of the array, can it change the structure of the documents, and has the output to be an array? I have to think about it.

sdorra commented 3 days ago

As I think about it more, I wonder if it makes sense to build such a function into the core. It is not easy to get the API right. What if a user needs the collection sorted by date and in another spot by title? This would not be possible with such an API, but sorting can be easily achieved outside of content collections, without repeating it in any spot:

Just create a file for example sorted.ts:

import { allPosts } from "content-collections";

export const postsSortedByDate = allPosts.toSorted(
  (a, b) => b.date.getTime() - a.date.getTime()
);

And if you want to use the sorted posts, just import them e.g.:

import { postsSortedByDate } from "sorted";

// do something with the sorted posts
sdorra commented 3 days ago

I think it is better to add a hint to the documentation instead of adding a new API. What do you think @n1ckoates?

n1ckoates commented 2 days ago

I agree, that makes a lot more sense!