UNPKG

1.47 kBJavaScriptView Raw
1/**
2 * YAML load and dump from/to JSON object.
3 * Support the loading of AWS Cloudformation intrinsinc function:
4 * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
5 */
6
7const fs = require('fs');
8const yaml = require('js-yaml');
9
10// Custom type for "!Ref"
11const refYamlType = new yaml.Type('!Ref', {
12 kind: 'scalar',
13 resolve: data => !!data && typeof data === 'string' && data.trim(),
14 construct: data => `!Ref ${data}`
15});
16
17// Custom type for "!GetAtt"
18const getattYamlType = new yaml.Type('!GetAtt', {
19 kind: 'scalar',
20 resolve: data => !!data && typeof data === 'string' && data.trim(),
21 construct: data => `!GetAtt ${data}`
22});
23
24// Create AWS schema for YAML parser
25const awsSchema = yaml.Schema.create(yaml.JSON_SCHEMA, [refYamlType, getattYamlType]);
26
27/**
28 * Load the yaml file with aws's schema
29 * @param {String} filePath File path for the yaml file
30 */
31function load(filePath) {
32 const fileData = fs.readFileSync(filePath, 'utf-8');
33 return yaml.safeLoad(fileData, { schema: awsSchema });
34}
35
36/**
37 * Dump the yaml file by merge the new content to the original file
38 * @param {String} filePath File path for the yaml file
39 * @param {Object} content Content to be written into filePath
40 */
41function dump(filePath, content) {
42 fs.writeFileSync(filePath, yaml.dump(content).replace(/: *'(.+)'/g, ': $1')); // remove the single quotes for the value
43}
44
45module.exports = {
46 load,
47 dump
48};