61 lines
1.4 KiB
JavaScript
Raw Normal View History

import yaml from 'js-yaml';
import moment from 'moment';
2017-01-10 22:23:22 -02:00
import AssetProxy from '../valueObjects/AssetProxy';
const MomentType = new yaml.Type('date', {
kind: 'scalar',
2017-01-10 22:23:22 -02:00
predicate(value) {
return moment.isMoment(value);
},
2017-01-10 22:23:22 -02:00
represent(value) {
return value.format(value._f);
},
2017-01-10 22:23:22 -02:00
resolve(value) {
return moment.isMoment(value) && value._f;
2017-01-10 22:23:22 -02:00
},
});
const ImageType = new yaml.Type('image', {
kind: 'scalar',
2017-01-10 22:23:22 -02:00
instanceOf: AssetProxy,
represent(value) {
return `${ value.path }`;
},
2017-01-10 22:23:22 -02:00
resolve(value) {
if (value === null) return false;
2017-01-10 22:23:22 -02:00
if (value instanceof AssetProxy) return true;
return false;
2017-01-10 22:23:22 -02:00
},
});
const OutputSchema = new yaml.Schema({
include: yaml.DEFAULT_SAFE_SCHEMA.include,
implicit: [MomentType, ImageType].concat(yaml.DEFAULT_SAFE_SCHEMA.implicit),
2017-01-10 22:23:22 -02:00
explicit: yaml.DEFAULT_SAFE_SCHEMA.explicit,
});
const sortKeys = (sortedKeys = []) => (a, b) => {
const idxA = sortedKeys.indexOf(a);
const idxB = sortedKeys.indexOf(b);
if (idxA === -1 || idxB === -1) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
if (idxA > idxB) return 1;
if (idxA < idxB) return -1;
return 0;
};
export default class YAML {
fromFile(content) {
return yaml.safeLoad(content);
}
toFile(data, sortedKeys = []) {
return yaml.safeDump(data, { schema: OutputSchema, sortKeys: sortKeys(sortedKeys) });
}
}