static-cms/src/formats/formats.js

68 lines
1.7 KiB
JavaScript
Raw Normal View History

import yamlFormatter from './yaml';
import tomlFormatter from './toml';
import jsonFormatter from './json';
import FrontmatterFormatter from './frontmatter';
export const supportedFormats = [
'yml',
'yaml',
'toml',
'json',
'frontmatter',
];
export const formatToExtension = format => ({
yml: 'yml',
yaml: 'yml',
toml: 'toml',
json: 'json',
frontmatter: 'md',
}[format]);
2016-09-11 23:08:18 +02:00
export function formatByExtension(extension) {
2016-09-13 14:53:50 +02:00
return {
2016-10-27 15:33:15 +02:00
yml: yamlFormatter,
yaml: yamlFormatter,
toml: tomlFormatter,
2016-10-27 15:33:15 +02:00
json: jsonFormatter,
md: FrontmatterFormatter,
markdown: FrontmatterFormatter,
html: FrontmatterFormatter,
}[extension] || FrontmatterFormatter;
2016-09-13 14:53:50 +02:00
}
function formatByName(name) {
return {
yml: yamlFormatter,
2016-10-27 15:33:15 +02:00
yaml: yamlFormatter,
toml: tomlFormatter,
2017-11-18 08:17:49 -07:00
json: jsonFormatter,
frontmatter: FrontmatterFormatter,
}[name];
2016-09-13 14:53:50 +02:00
}
2016-09-06 13:04:17 -03:00
export function resolveFormat(collectionOrEntity, entry) {
// If the format is specified in the collection, use that format.
const format = collectionOrEntity.get('format');
if (format) {
return formatByName(format);
2016-09-11 23:08:18 +02:00
}
// If a file already exists, infer the format from its file extension.
const filePath = entry && entry.path;
if (filePath) {
const fileExtension = filePath.split('.').pop();
return formatByExtension(fileExtension);
}
// If creating a new file, and an `extension` is specified in the
// collection config, infer the format from that extension.
const extension = collectionOrEntity.get('extension');
if (extension) {
return formatByExtension(extension);
}
// If no format is specified and it cannot be inferred, return the default.
return formatByName('frontmatter');
}