static-cms/src/formats/formats.js
Caleb 864083bc8b Infer format from extension for new entries.
If a collection has no format specified, we try to infer the format from
the file extension when reading. This commit also allows us to infer the
format from the `extension` set in the config, so that we can still
create the correct format when making a new file.
2017-12-06 10:07:07 -05:00

60 lines
1.6 KiB
JavaScript

import yamlFormatter from './yaml';
import tomlFormatter from './toml';
import jsonFormatter from './json';
import FrontmatterFormatter from './frontmatter';
export const formatToExtension = format => ({
markdown: 'md',
yaml: 'yml',
toml: 'toml',
json: 'json',
html: 'html',
}[format]);
export function formatByExtension(extension) {
return {
yml: yamlFormatter,
yaml: yamlFormatter,
toml: tomlFormatter,
json: jsonFormatter,
md: FrontmatterFormatter,
markdown: FrontmatterFormatter,
html: FrontmatterFormatter,
}[extension] || FrontmatterFormatter;
}
function formatByName(name) {
return {
yml: yamlFormatter,
yaml: yamlFormatter,
toml: tomlFormatter,
json: jsonFormatter,
frontmatter: FrontmatterFormatter,
}[name] || FrontmatterFormatter;
}
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);
}
// 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();
}