Add lib file
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Jared He 2021-07-27 15:45:19 -05:00
parent 6a64013e5c
commit b733acd156
1 changed files with 60 additions and 0 deletions

60
lib/events.ts Normal file
View File

@ -0,0 +1,60 @@
import fs from "fs/promises";
import path from "path";
import matter from "gray-matter";
import { serialize } from "next-mdx-remote/serialize";
import { MDXRemoteSerializeResult } from "next-mdx-remote";
const EVENTS_PATH = path.join("content", "events");
export async function getYears(): Promise<string[]> {
return await fs.readdir(EVENTS_PATH);
}
export async function getTermsByYear(year: string): Promise<string[]> {
return await fs.readdir(path.join(EVENTS_PATH, year));
}
interface Metadata {
name: string;
short: string;
date: string;
online: boolean;
location: string;
}
export interface Event {
content: string | MDXRemoteSerializeResult<Record<string, unknown>>;
metadata: Metadata;
}
export async function getEventBySlug(
year: string,
term: string,
slug: string,
convert = true
): Promise<Event> {
const raw = await fs.readFile(
path.join(EVENTS_PATH, year, term, `${slug}.event.md`),
"utf-8"
);
const { content, data: metadata } = matter(raw);
return {
content: convert ? await serialize(content) : content,
metadata: metadata as Metadata,
};
}
export async function getEventsByTerm(
year: string,
term: string
): Promise<Event[]> {
const files = (await fs.readdir(path.join(EVENTS_PATH, year, term)))
.filter((name) => name.endsWith(".event.md"))
.map((name) => name.slice(0, -".event.md".length));
const props = await Promise.all(
files.map((file) => getEventBySlug(year, term, file))
);
return props;
}