Skip to content

Instantly share code, notes, and snippets.

@jasikpark
Created October 31, 2022 17:37
Show Gist options
  • Save jasikpark/0ac71a791a2745f68e7a64b935e5c6e6 to your computer and use it in GitHub Desktop.
Save jasikpark/0ac71a791a2745f68e7a64b935e5c6e6 to your computer and use it in GitHub Desktop.
Helper function at `src/pages/blog/_getAllPublishablePosts.ts`
import { assert } from "assert-ts";
import type { MarkdownInstance, MDXInstance } from "astro";
import type { MarkdownFrontmatter } from "@data/posts/MarkdownFrontmatter";
export type MarkdownOrMDXInstance =
| MarkdownInstance<MarkdownFrontmatter>
| MDXInstance<MarkdownFrontmatter>;
type PartialMarkdownOrMDXInstance =
| MarkdownInstance<Partial<MarkdownFrontmatter>>
| MDXInstance<Partial<MarkdownFrontmatter>>;
/** getAllPublishablePosts returns all `/blog` MD and MDX posts, validated in their shape:
all posts that have a slug and date and aren't hidden, and sort by date. */
export function getAllPublishablePosts(): MarkdownOrMDXInstance[] {
const allMdPages = import.meta.glob("../../data/posts/*.md", {
eager: true,
}) as Record<string, MarkdownInstance<Partial<MarkdownFrontmatter>>>;
const allMdxPages = import.meta.glob("../../data/posts/**/*.mdx", {
eager: true,
}) as Record<string, MDXInstance<Partial<MarkdownFrontmatter>>>;
const allPages = (
Object.values({ ...allMdPages, ...allMdxPages }) as PartialMarkdownOrMDXInstance[]
)
.filter(function (post): post is MarkdownOrMDXInstance {
const missingError = (prop: string) => `post ${post.file.toString()} has no ${prop}`;
assert(post.frontmatter.title, missingError("title"));
assert(post.frontmatter.summary, missingError("summary"));
assert(post.frontmatter.hero, missingError("hero"));
assert(post.frontmatter.hero?.src, missingError("hero.src"));
assert(post.frontmatter.hero?.alt, missingError("hero.alt"));
return !!post.frontmatter.slug && !!post.frontmatter.date && !post.frontmatter.hide;
})
.sort(
(a, b) => new Date(b.frontmatter.date).valueOf() - new Date(a.frontmatter.date).valueOf()
);
return allPages;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment