-
Notifications
You must be signed in to change notification settings - Fork 29
/
utils.js
320 lines (275 loc) · 9.05 KB
/
utils.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import onChange from 'on-change'
import lodash from 'lodash'
import fs from 'fs-extra'
import chalk from 'chalk'
import { parseError } from '../../utils'
import migrationTemplate from '../templates/migration-file'
const { isArray, isPlainObject, has, isEmpty, template, truncate } = lodash
const MIGRATIONS_DIRECTORY = `${process.cwd()}/migrations`
const MIGRATIONS_ROLLBACK_DIRECTORY = `${process.cwd()}/migrations/rollback`
/**
* @method getPathToFile
* @param {String} fileName name of the file
* @param {String} migrationPath migrations folder
* @return {String}
*
* @example
* // path/to/migrations/change_teaser_subtitle.js
* getPathToFile('change_teaser_subtitle.js')
*
* // ./migrations/change_teaser_subtitle.js
* getPathToFile('change_teaser_subtitle.js', './migrations')
*/
export const getPathToFile = (fileName, migrationPath = null) => {
const pathTo = isEmpty(migrationPath) ? MIGRATIONS_DIRECTORY : migrationPath
return `${pathTo}/${fileName}`
}
/**
* @method getNameOfMigrationFile
* @param {String} component name of component
* @param {String} field name of component's field
* @return {String}
*
* @example
* getNameOfMigrationFile('product', 'price') // change_product_price
*/
export const getNameOfMigrationFile = (component, field) => {
return `change_${component}_${field}.mjs`
}
/**
* @method getComponentsFromName
* @param {Object} api API Object
* @param {String} component name of component
* @return {Promise<Array>}
*/
export const getStoriesByComponent = async (api, componentName) => {
try {
const stories = await api.getStories({
contain_component: componentName
})
return stories
} catch (e) {
const error = parseError(e)
console.error(`${chalk.red('X')} An error ocurred when load the stories filtering by component ${componentName}: ${error.message}`)
return Promise.reject(error.error)
}
}
/**
* @method getComponentsFromName
* @param {Object} api API Object
* @param {String} component name of component
* @return {Promise<Object>}
*/
export const getComponentsFromName = async (api, componentName) => {
try {
const components = await api.getComponents()
const found = components.filter(_comp => {
return _comp.name === componentName
})
if (found.length > 0) {
return Promise.resolve(found[0])
}
return {}
} catch (e) {
const error = parseError(e)
console.error(`${chalk.red('X')} An error occurred when loading the components from space: ${error.message}`)
return Promise.reject(error.error)
}
}
/**
* @method checkComponentExists
* @param {Object} api API Object
* @param {String} component name of component
* @return {Promise<Boolean>}
*/
export const checkComponentExists = async (api, component) => {
try {
const componentData = await getComponentsFromName(api, component)
return Promise.resolve(Object.keys(componentData).length > 0)
} catch (e) {
const error = parseError(e)
return Promise.reject(error.error)
}
}
/**
* @method checkFileExists
* @param {String} filePath
* @return {Promise<Boolean>}
*/
export const checkFileExists = async (filePath) => fs.pathExists(filePath)
/**
* @method createMigrationFile
* @param {String} fileName path to file
* @param {String} field name of the field
* @return {Promise<Boolean>}
*/
export const createMigrationFile = (fileName, field) => {
console.log(`${chalk.blue('-')} Creating the migration file in migrations folder`)
// use lodash.template to replace the occurrences of fieldname
const compile = template(migrationTemplate, {
interpolate: /{{([\s\S]+?)}}/g
})
const outputMigrationFile = compile({
fieldname: field
})
return fs.outputFile(getPathToFile(fileName), outputMigrationFile)
}
/**
* @method getInquirerOptions
* @param {String} type
* @return {Array}
*/
export const getInquirerOptions = (type) => {
if (type === 'file-exists') {
return [{
type: 'confirm',
name: 'choice',
message: 'Do you want to continue? (This will overwrite the content of the file!)'
}]
}
return []
}
/**
* @method showMigrationChanges
* @param {String} path field name
* @param {unknown} value updated value
* @param {unknown} oldValue previous value
*/
export const showMigrationChanges = (path, value, oldValue) => {
// It was created a new field
if (oldValue === undefined) {
// truncate the string with more than 30 characters
const _value = truncate(value)
console.log(` ${chalk.green('-')} Created field "${chalk.green(path)}" with value "${chalk.green(_value)}"`)
return
}
// It was removed the field
if (value === undefined) {
console.log(` ${chalk.red('-')} Removed the field "${chalk.red(path)}"`)
return
}
// It was updated the value
if (value !== oldValue) {
// truncate the string with more than 30 characters
const _value = truncate(value)
const _oldValue = truncate(oldValue)
console.log(` ${chalk.blue('-')} Updated field "${chalk.blue(path)}" from "${chalk.blue(_oldValue)}" to "${chalk.blue(_value)}"`)
}
}
/**
* @method processMigration
* @param {Object} content component structure from Storyblok
* @param {String} component name of the component that is processing
* @param {Function} migrationFn the migration function defined by user
* @param {String} storyFullSlug the full slug of the containing story
* @return {Promise<Boolean>}
*/
export const processMigration = async (content = {}, component = '', migrationFn, storyFullSlug) => {
// I'm processing the component that I want
if (content.component === component) {
const watchedContent = onChange(
content,
showMigrationChanges
)
await migrationFn(watchedContent, storyFullSlug)
}
for (const key in content) {
const value = content[key]
if (isArray(value)) {
try {
await Promise.all(
value.map(_item => processMigration(_item, component, migrationFn, storyFullSlug))
)
} catch (e) {
console.error(e)
}
}
if (isPlainObject(value) && has(value, 'component')) {
try {
await processMigration(value, component, migrationFn, storyFullSlug)
} catch (e) {
console.error(e)
}
}
if (isPlainObject(value) && value.type === 'doc' && value.content) {
value.content.filter(item => item.type === 'blok').forEach(async (item) => {
try {
await processMigration(item.attrs.body, component, migrationFn, storyFullSlug)
} catch (e) {
console.error(e)
}
})
}
}
return Promise.resolve(true)
}
/**
* @method urlTofRollbackMigrationFile
* @param {String} component name of the component to rollback
* @param {String} field name of the field to rollback
* @return {String}
*/
export const urlTofRollbackMigrationFile = (component, field) => {
return `${MIGRATIONS_ROLLBACK_DIRECTORY}/${getNameOfRollbackMigrationFile(component, field)}`
}
/**
* @method getNameOfRollbackMigrationFile
* @param {String} component name of the component to rollback
* @param {String} field name of the field to rollback
* @return {String}
*/
export const getNameOfRollbackMigrationFile = (component, field) => {
return `rollback_${component}_${field}.json`
}
/**
* @method createRollbackFile
* @param {Array} stories array containing stories for rollback
* @return {Promise}
*/
export const createRollbackFile = async (stories, component, field) => {
try {
if (!fs.existsSync(MIGRATIONS_ROLLBACK_DIRECTORY)) {
fs.mkdir(MIGRATIONS_ROLLBACK_DIRECTORY)
}
const url = urlTofRollbackMigrationFile(component, field)
if (fs.existsSync(url)) {
fs.unlinkSync(url)
}
fs.writeFile(url, JSON.stringify(stories, null, 2), { flag: 'a' }, (error) => {
if (error) {
console.log(`${chalk.red('X')} The rollback file could not be created: ${error}`)
return error
}
console.log(`${chalk.green('✓')} The rollback file has been created in migrations/rollback/!`)
})
return Promise.resolve({
component: component,
created: true
})
} catch (error) {
return Promise.reject(error)
}
}
/**
* @method checkExistenceFilesInRollBackDirectory
* @param {String} path path of the rollback folder directories
* @param {String} component name of the components to be searched for in the rollback folder
* @param {String} field name of the field to be searched for in the rollback folder
* @return {Promisse<Array>}
*/
export const checkExistenceFilesInRollBackDirectory = (path, component, field) => {
if (!fs.existsSync(path)) {
console.log(`
${chalk.red('X')} The path for which the rollback files should be contained does not exist`
)
return Promise.reject(new Error({ error: 'Path not found' }))
}
const files = fs.readdirSync(path).map(file => file)
const file = files.filter((name) => {
const splitedName = name.split('_')
if (splitedName[1] === component && splitedName[2] === `${field}.json`) {
return name
}
})
return Promise.resolve(file)
}