From 5283ed6dc34ee32c67b9f10b0e4aad556401896d Mon Sep 17 00:00:00 2001 From: Devin Haska Date: Tue, 6 Feb 2024 23:00:04 -0800 Subject: [PATCH] feat: add methods to fetch post categories --- config/collections/index.js | 32 ++++++++++++++++++++++++++++++++ eleventy.config.js | 4 ++++ 2 files changed, 36 insertions(+) create mode 100644 config/collections/index.js diff --git a/config/collections/index.js b/config/collections/index.js new file mode 100644 index 0000000..c886e13 --- /dev/null +++ b/config/collections/index.js @@ -0,0 +1,32 @@ +const path = require("path"); +const { dir } = require("../constants.js"); + +const getAllPosts = (collection) => { + const posts = collection.getFilteredByGlob( + path.join(dir.input, "content/posts/**/*.md"), + ); + return posts.reverse(); +}; + +const getAllPostCategories = (collection) => { + const posts = getAllPosts(collection); + + const allCategories = posts.flatMap((post) => post.data.categories); + + const categories = allCategories.reduce((acc, category) => { + if (acc[category]) { + acc[category]++; + } else { + acc[category] = 1; + } + + return acc; + }, {}); + + return categories; +}; + +module.exports = { + getAllPosts, + getAllPostCategories, +}; diff --git a/eleventy.config.js b/eleventy.config.js index d5a2e78..bed958d 100644 --- a/eleventy.config.js +++ b/eleventy.config.js @@ -14,11 +14,15 @@ const imageShortcode = require("./config/shortcodes/image.js"); module.exports = (eleventyConfig) => { eleventyConfig.addWatchTarget("./src/assets"); + // --------------------- Custom Template Languages --------------------- eleventyConfig.addPlugin( require("./config/template-languages/css-config.js"), ); + eleventyConfig.addCollection("posts", getAllPosts); + eleventyConfig.addCollection("categories", getAllPostCategories); + // --------------------- Custom Filters ----------------------- eleventyConfig.addFilter("entries", entries); eleventyConfig.addFilter("formatDate", formatDate);