static-cms/src/formats/frontmatter.js

39 lines
932 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';
import YAML from './yaml';
2017-04-07 22:40:30 +01:00
// Automatically register parsers
preliminaries(true);
yamlParser(true);
tomlParser(true);
export default class Frontmatter {
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
});
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 });
}
}