static-cms/src/formats/frontmatter.js
2017-09-15 19:22:04 -06:00

51 lines
1.3 KiB
JavaScript

import preliminaries from 'preliminaries';
import yamlParser from 'preliminaries-parser-yaml';
import tomlParser from 'preliminaries-parser-toml';
import YAML from './yaml';
// Automatically register parsers
preliminaries(true);
yamlParser(true);
tomlParser(true);
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) {
const result = preliminaries.parse(content, inferFrontmatterFormat(content));
const data = result.data;
data.body = result.content;
return data;
}
toFile(data, sortedKeys) {
const meta = {};
let body = '';
Object.keys(data).forEach((key) => {
if (key === 'body') {
body = data[key];
} else {
meta[key] = data[key];
}
});
// always stringify to YAML
const parser = {
stringify(metadata) {
return new YAML().toFile(metadata, sortedKeys);
},
};
return preliminaries.stringify(body, meta, { lang: "yaml", delims: "---", parser });
}
}