initiation librodrome
This commit is contained in:
30
server/api/admin/chapters/[slug].get.ts
Normal file
30
server/api/admin/chapters/[slug].get.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const slug = getRouterParam(event, 'slug')
|
||||
|
||||
if (!slug || !/^[a-z0-9-]+$/.test(slug)) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Invalid slug' })
|
||||
}
|
||||
|
||||
const filePath = join(process.cwd(), 'content', 'book', `${slug}.md`)
|
||||
|
||||
try {
|
||||
const raw = await readFile(filePath, 'utf-8')
|
||||
const fmMatch = raw.match(/^---\n([\s\S]*?)\n---\n?/)
|
||||
|
||||
let frontmatter = ''
|
||||
let body = raw
|
||||
|
||||
if (fmMatch) {
|
||||
frontmatter = fmMatch[1]
|
||||
body = raw.slice(fmMatch[0].length)
|
||||
}
|
||||
|
||||
return { slug, frontmatter, body }
|
||||
}
|
||||
catch {
|
||||
throw createError({ statusCode: 404, statusMessage: `Chapter "${slug}" not found` })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user