|
| 1 | +import fs from 'fs' |
| 2 | +import path from 'path' |
| 3 | +import matter from 'gray-matter' |
| 4 | +import { marked } from 'marked' |
| 5 | + |
| 6 | +const ACADEMIA_DIRECTORY = path.join(process.cwd(), 'content', 'academia') |
| 7 | + |
| 8 | +const normalizeMaintainerProfiles = (maintainerProfiles = []) => { |
| 9 | + if (Array.isArray(maintainerProfiles)) { |
| 10 | + return maintainerProfiles.reduce( |
| 11 | + (profiles, entry) => ({ ...profiles, ...entry }), |
| 12 | + {}, |
| 13 | + ) |
| 14 | + } |
| 15 | + |
| 16 | + if (maintainerProfiles && typeof maintainerProfiles === 'object') { |
| 17 | + return maintainerProfiles |
| 18 | + } |
| 19 | + |
| 20 | + return {} |
| 21 | +} |
| 22 | + |
| 23 | +const parsePost = ({ slug, data, content }) => ({ |
| 24 | + slug, |
| 25 | + name: data.name || '', |
| 26 | + institution: data.institution || '', |
| 27 | + department: data.department || '', |
| 28 | + projectName: data.projectName || '', |
| 29 | + projectRepo: data.projectRepo || '', |
| 30 | + projectWebsite: data.projectWebsite || '', |
| 31 | + maintainerProfiles: normalizeMaintainerProfiles(data.maintainerProfiles), |
| 32 | + badges: Array.isArray(data.badges) ? data.badges : [], |
| 33 | + description: data.description || '', |
| 34 | + content, |
| 35 | +}) |
| 36 | + |
| 37 | +export const getAcademiaPosts = () => { |
| 38 | + if (!fs.existsSync(ACADEMIA_DIRECTORY)) { |
| 39 | + return [] |
| 40 | + } |
| 41 | + |
| 42 | + return fs |
| 43 | + .readdirSync(ACADEMIA_DIRECTORY) |
| 44 | + .filter((fileName) => fileName.endsWith('.md')) |
| 45 | + .map((fileName) => { |
| 46 | + const slug = fileName.replace('.md', '') |
| 47 | + const markdown = fs.readFileSync( |
| 48 | + path.join(ACADEMIA_DIRECTORY, fileName), |
| 49 | + 'utf-8', |
| 50 | + ) |
| 51 | + const { data, content } = matter(markdown) |
| 52 | + |
| 53 | + return parsePost({ slug, data, content }) |
| 54 | + }) |
| 55 | + .sort((postA, postB) => postA.projectName.localeCompare(postB.projectName)) |
| 56 | +} |
| 57 | + |
| 58 | +export const getAcademiaPostBySlug = (slug) => { |
| 59 | + const filePath = path.join(ACADEMIA_DIRECTORY, `${slug}.md`) |
| 60 | + |
| 61 | + if (!fs.existsSync(filePath)) { |
| 62 | + return null |
| 63 | + } |
| 64 | + |
| 65 | + const markdown = fs.readFileSync(filePath, 'utf-8') |
| 66 | + const { data, content } = matter(markdown) |
| 67 | + const post = parsePost({ slug, data, content }) |
| 68 | + |
| 69 | + return { |
| 70 | + ...post, |
| 71 | + htmlContent: marked(post.content), |
| 72 | + } |
| 73 | +} |
0 commit comments