Skip to content

Commit

Permalink
Add Markdown getter API
Browse files Browse the repository at this point in the history
  • Loading branch information
nkokla committed Aug 28, 2024
1 parent 73cfe5c commit de5827c
Showing 1 changed file with 88 additions and 0 deletions.
88 changes: 88 additions & 0 deletions src/lib/markdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { join } from 'node:path'
import * as fs from 'node:fs/promises'
import { remark } from 'remark'
import remarkHeadingId from 'remark-heading-id'

import html from 'remark-html'
import matter from 'gray-matter'

const { NEXT_PUBLIC_ADRESSE_URL, NODE_ENV } = process.env

// fix unknown property on matter.GrayMatterFile
// https://github.com/jonschlinkert/gray-matter/issues/160
interface GreyMatter extends matter.GrayMatterFile<string> {
isEmpty?: boolean
}

export type DataType = {
aside?: Array<{ data: { contentHtml: string, data: { title: string } } }>
}

export type MarkdownType = {
fileName: string,
excerpt?: string,
contentHtml?: string,
data?: DataType,
isEmpty?: boolean,
}

const extractMarkdown = async (
fileContents: string,
callback: (filename: string, host?: string | undefined) => Promise<{}>,
filename: string,
host?: string
): Promise<MarkdownType> => {
const { content, data = {}, excerpt, isEmpty }: GreyMatter = matter(fileContents)

const processedContent = await remark()
.use(remarkHeadingId, { defaults: true, uniqueDefaults: true })
.use(html)
.process(content)
const contentHtml = processedContent.toString()

let aside
if (!isEmpty && data?.aside) {
try {
const asideContent = data.aside.map(
(aside: { filename: string | undefined }) => aside?.filename && callback(aside.filename, host)
)
aside = (await Promise.all(asideContent)).map((content, i) => ({ ...data.aside[i], data: content }))
}
catch (error) {
if (NODE_ENV === 'development') console.error(error)
}
}

return {
fileName: filename,
excerpt,
contentHtml,
data: { ...data, ...(aside ? { aside } : {}) },
isEmpty,
}
}

export async function getMarkdown(filename: string = 'sample') {
'use server'

try {
const filePath = join(process.cwd(), 'public', 'markdown', `${filename}.md`);
const fileContents = await fs.readFile(filePath, 'utf8');
return extractMarkdown(fileContents, getMarkdown, filename)
}
catch (error) {
if (NODE_ENV === 'development') console.error(error)
return {}
}
}

export async function fetchMarkdown(filename: string = 'sample', host = NEXT_PUBLIC_ADRESSE_URL) {
try {
const fileContents = await fetch(`${host}/markdown/${filename}.md`).then(response => response.text())
return extractMarkdown(fileContents, fetchMarkdown, filename, host)
}
catch (error) {
if (NODE_ENV === 'development') console.error(error)
return {}
}
}

0 comments on commit de5827c

Please sign in to comment.