nuxt / content

The file-based CMS for your Nuxt application, powered by Markdown and Vue components.
https://content.nuxt.com
MIT License
3.13k stars 627 forks source link

Add `rawBody` property to parsed content #2803

Open oneminch opened 1 month ago

oneminch commented 1 month ago

Is your feature request related to a problem? Please describe

The beforeParse hook provides access to the raw Markdown body, while afterParse provides access to parsed content.

Since adding custom properties to the file object is not allowed in beforeParse, it would be helpful to optionally make the raw Markdown body accessible from file object in afterParse.

For example, when implementing a word count functionality (as discussed here), the ideal solution would have been to count the words of the raw Markdown text inside the beforeParse hook and add the value to a file.wordCount property. But, adding a property to file is not allowed, so the workaround is to add the value to the file.body as a plain Markdown text, and get the value from the parsed body inside afterParse hook. Then a custom wordCount property can be added to the file object. (Workaround solution)

Describe the solution you'd like

For scenarios like the one described above, it would be useful to add a rawBody property to the file argument of the afterParse hook callback.

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook("content:file:afterParse", (file) => {
    if (file._id.endsWith(".md")) {
      // Currently raw body is not accessible from the afterParse hook
      const wordCount = countWords(file.rawBody);

      file.wordCount = wordCount;
    }
  });
});

Describe alternatives you've considered

An alternative solution for such a case would be to allow developers to add custom properties to the file argument of the beforeParse hook callback.

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook("content:file:beforeParse", (file) => {
    if (file._id.endsWith(".md")) {
      const wordCount = countWords(file.body);

      // Currently not allowed in the beforeParse hook
      file.wordCount = wordCount;
    }
  });
});

Additional context

If implemented, the feature would solve problems like this one - Get amount of words in an article (#2795)