static-cms/src/formats/frontmatter.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

import matter from 'gray-matter';
import tomlEng from 'toml';
import YAML from './yaml';
2017-09-12 20:51:40 -06:00
function inferFrontmatterFormat(str) {
const firstLine = str.substr(0, str.indexOf('\n')).trim();
switch (firstLine) {
case "---":
return { language: "yaml", delimiters: "---" };
2017-09-12 20:51:40 -06:00
case "+++":
return { language: "toml", delimiters: "+++", engines: { toml: tomlEng.parse.bind(tomlEng) } };
2017-09-12 20:51:40 -06:00
case "{":
return { language: "json", delimiters: ["{", "}"] };
2017-09-12 20:51:40 -06:00
}
}
export default class Frontmatter {
fromFile(content) {
const result = matter(content, inferFrontmatterFormat(content));
2017-04-07 22:40:30 +01:00
const data = result.data;
data.body = result.content;
return data;
}
toFile(data, sortedKeys) {
const meta = {};
let body = '';
2017-04-07 22:40:30 +01:00
Object.keys(data).forEach((key) => {
if (key === 'body') {
body = data[key];
} else {
meta[key] = data[key];
}
2017-04-07 22:40:30 +01:00
});
2017-04-07 22:40:30 +01:00
// always stringify to YAML
const parser = {
stringify(metadata) {
return new YAML().toFile(metadata, sortedKeys);
},
};
return matter.stringify(body, meta, { language: "yaml", delimiters: "---", engines: { yaml: parser } });
}
}