static-cms/src/formats/yaml-frontmatter.js

32 lines
779 B
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';
2017-04-07 22:40:30 +01:00
// Automatically register parsers
preliminaries(true);
yamlParser(true);
tomlParser(true);
export default class YAMLFrontmatter {
fromFile(content) {
2017-04-07 22:40:30 +01:00
const result = preliminaries.parse(content);
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
});
// always stringify to YAML
return preliminaries.stringify(body, meta, { lang: 'yaml', delims: '---' });
}
}