Created
December 12, 2023 15:37
-
-
Save sannajammeh/59338657448e9cb901609730bce605bc to your computer and use it in GitHub Desktop.
Astro content collections orderBy pseudo code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { z } from "zod"; | |
const schema = z.object({ | |
date: z.date(), | |
}); | |
const postCollection = { | |
type: "content", | |
schema: schema, | |
orderBy: [(s: z.infer<typeof schema>) => s.date, "DESC"], | |
}; | |
const collections = { | |
blog: postCollection, | |
} as const; | |
const dummyData = [ | |
{ | |
date: new Date("2021-01-01"), | |
}, | |
{ | |
date: new Date("2021-01-03"), | |
}, | |
{ | |
date: new Date("2021-01-02"), | |
}, | |
]; | |
const getCollection = async (key: keyof typeof collections) => { | |
const collectionConfig = collections[key]; | |
const data = dummyData.map((d) => { | |
const res = collectionConfig.schema.safeParse(d); | |
if (!res.success) throw new Error("Invalid data"); | |
return res.data; | |
}); | |
const [orderBy, DIR] = (collectionConfig.orderBy ?? []) as [ | |
Function, | |
"ASC" | "DESC", | |
]; | |
if (!orderBy) return data; | |
const sortedData = data.toSorted((a, b) => { | |
const aOrderBy = orderBy(a); | |
const bOrderBy = orderBy(b); | |
switch (DIR) { | |
case "ASC": | |
return aOrderBy < bOrderBy ? -1 : 1; | |
case "DESC": | |
return aOrderBy < bOrderBy ? 1 : -1; | |
default: | |
throw new Error("Invalid direction"); | |
} | |
}); | |
return sortedData; | |
}; | |
const data = await getCollection("blog"); | |
console.log(data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment