static-cms/src/formats/frontmatter.js

51 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-04-07 22:40:30 +01:00
import preliminaries from 'preliminaries';
import yamlParser from 'preliminaries-parser-yaml';
import tomlParser from 'preliminaries-parser-toml';
import YAML from './yaml';
2017-04-07 22:40:30 +01:00
// Automatically register parsers
preliminaries(true);
yamlParser(true);
tomlParser(true);
2017-09-12 20:51:40 -06:00
function inferFrontmatterFormat(str) {
const firstLine = str.substr(0, str.indexOf('\n')).trim();
switch (firstLine) {
case "---":
return { lang: "yaml", delims: "---" };
case "+++":
return { lang: "toml", delims: "+++" };
case "{":
return { lang: "json", delims: ["{", "}"] };
}
}
export default class Frontmatter {
fromFile(content) {
2017-09-12 20:51:40 -06:00
const result = preliminaries.parse(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 preliminaries.stringify(body, meta, { lang: "yaml", delims: "---", parser });
}
}