Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: call hooks before and after parse #1160

Merged
merged 15 commits into from May 31, 2022
19 changes: 13 additions & 6 deletions src/runtime/server/transformers/index.ts
@@ -1,23 +1,27 @@
import { extname } from 'pathe'
import type { ParsedContent, ContentTransformer } from '../../types'
import { getParser, getTransformers } from '#content/virtual/transformers'

// eslint-disable-next-line import/named
import { useNitroApp } from '#imports'
/**
* Parse content file using registered plugins
*/
export async function parseContent (id: string, content: string) {
const nitroApp = useNitroApp()

// Call hook before parsing the file
const file = { _id: id, content }
await nitroApp.hooks.callHook('content:file:beforeParse', file)

const ext = extname(id)
const plugin: ContentTransformer = getParser(ext)
if (!plugin) {
// eslint-disable-next-line no-console
console.warn(`${ext} files are not supported, "${id}" falling back to raw content`)
return {
_id: id,
body: content
}
return file
}

const parsed: ParsedContent = await plugin.parse!(id, content)
const parsed: ParsedContent = await plugin.parse!(file._id, file.content)

const transformers = getTransformers(ext)
const result = await transformers.reduce(async (prev, cur) => {
Expand All @@ -26,5 +30,8 @@ export async function parseContent (id: string, content: string) {
return cur.transform!(next)
}, Promise.resolve(parsed))

// Call hook after parsing the file
await nitroApp.hooks.callHook('content:file:afterParse', result)

return result
}