-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
220 lines (183 loc) · 7.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
const inquirerTablePrompt = require('inquirer-table-prompt');
const pkg = require('./package.json');
const slugify = require('@sindresorhus/slugify');
const { getSetupForData, getSetupForPage } = require('./lib/setup');
module.exports.name = pkg.name;
module.exports.transform = ({ data, debug, log, options }) => {
if (typeof options.writeFile !== 'function') {
return data;
}
const utils = {
slugify: input => {
if (typeof input !== 'string' || input.trim().length === 0) {
throw new Error('ERROR_FAILED_SLUGIFY');
}
return slugify(input);
}
};
const files = data.objects.reduce((result, object) => {
try {
const writer = options.writeFile(object, utils);
if (!writer) return result;
return result.concat(writer);
} catch (error) {
const objectDetails = object && object.__metadata && object.__metadata.id ? ` (Object ID: ${object.__metadata.id})` : '';
if (error.message === 'ERROR_FAILED_SLUGIFY') {
log(`Could not write object to disk because \`slugify()\` was used on an empty field.${objectDetails}`, 'fail');
debug(error);
} else {
log(`Could not write object to disk.${objectDetails} `, 'fail');
debug(error);
}
return result;
}
}, []);
return {
...data,
files: (data.files || []).concat(files)
};
};
module.exports.getOptionsFromSetup = ({ answers, debug }) => {
const { data: dataObjects = [], pages = [] } = answers;
const conditions = [];
pages.forEach(page => {
const { modelName, projectId, source } = page.__model;
let location = '';
if (page.location.fileName) {
location = `'${page.location.fileName}'`;
} else {
const { directory, fileNameField, useDate } = page.location;
const locationParts = [];
if (directory) {
locationParts.push(`'${directory}/'`);
}
if (useDate) {
locationParts.push(`createdAt.substring(0, 10) + '-'`);
}
locationParts.push(`utils.slugify(fields['${fileNameField}']) + '.md'`);
location = locationParts.join(' + ');
}
const contentField = page.contentField ? `fields['${page.contentField}']` : '{}';
const layout = page.layoutSource === 'static' ? `'${page.layout}'` : `fields['${page.layout}']`;
const extractedProperties = [
'__metadata',
page.contentField ? `'${page.contentField}': content` : null,
page.layoutSource ? 'layout' : null,
'...frontmatterFields'
];
const conditionParts = [
modelName && `modelName === '${modelName}'`,
projectId && `projectId === '${projectId}'`,
source && `source === '${source}'`
].filter(Boolean);
conditions.push(
`if (${conditionParts.join(' && ')}) {`,
` const { ${extractedProperties.filter(Boolean).join(', ')} } = entry;`,
``,
` return {`,
` content: {`,
` body: ${contentField},`,
` frontmatter: ${page.layoutSource ? `{ ...frontmatterFields, layout: ${layout} }` : 'frontmatterFields'},`,
` },`,
` format: 'frontmatter-md',`,
` path: ${location}`,
` };`,
`}\n`
);
});
dataObjects.forEach(dataObject => {
const { modelName, projectId, source } = dataObject.__model;
const { format, isMultiple } = dataObject;
const location = dataObject.location.fileName
? `'${dataObject.location.fileName}'`
: `fields['${dataObject.location.fileNameField}']`;
conditions.push(
`if (modelName === '${modelName}' && projectId === '${projectId}' && source === '${source}') {`,
` const { __metadata, ...fields } = entry;`,
``,
` return {`,
` append: ${isMultiple},`,
` content: fields,`,
` format: '${format}',`,
` path: ${location}`,
` };`,
`}\n`
);
});
const functionBody = `
// This function is invoked for each entry and its return value determines
// whether the entry will be written to a file. When an object with \`content\`,
// \`format\` and \`path\` properties is returned, a file will be written with
// those parameters. If a falsy value is returned, no file will be created.
const { __metadata: meta, ...fields } = entry;
if (!meta) return;
const { createdAt = '', modelName, projectId, source } = meta;
${conditions.join('\n')}
`.trim();
debug('Function body: %s', functionBody);
return {
writeFile: new Function('entry', 'utils', functionBody)
};
};
module.exports.getSetup = ({ chalk, data, inquirer }) => {
inquirer.registerPrompt('table', inquirerTablePrompt);
return async () => {
const { models: modelTypes } = await inquirer.prompt([
{
type: 'table',
name: 'models',
message: 'Choose a type for each of the following models:',
pageSize: 7,
rows: data.models.map((model, index) => ({
name: `${model.modelLabel || model.modelName}\n${chalk.dim(`└${model.source}`)}`,
value: index
})),
columns: [
{
name: 'Page',
value: 'page'
},
{
name: 'Data',
value: 'data'
},
{
name: 'Skip',
value: undefined
}
]
}
]);
const dataModels = [];
const pageModels = [];
modelTypes.forEach((type, index) => {
if (type === 'data') {
dataModels.push(data.models[index]);
} else if (type === 'page') {
pageModels.push(data.models[index]);
}
});
let queue = Promise.resolve({ data: [], pages: [] });
pageModels.forEach((model, index) => {
queue = queue.then(async setupData => {
console.log(
`\nConfiguring page: ${chalk.bold(model.modelLabel || model.modelName)} ${chalk.reset.italic.green(
`(${index + 1} of ${pageModels.length}`
)})`
);
return getSetupForPage({ chalk, data, inquirer, model, setupData });
});
});
dataModels.forEach((model, index) => {
queue = queue.then(async setupData => {
console.log(
`\nConfiguring data object: ${chalk.bold(model.modelLabel || model.modelName)} ${chalk.reset.italic.green(
`(${index + 1} of ${dataModels.length}`
)})`
);
return getSetupForData({ chalk, data, inquirer, model, setupData });
});
});
return queue;
};
};