-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathvalidations.ts
More file actions
55 lines (49 loc) · 1.81 KB
/
validations.ts
File metadata and controls
55 lines (49 loc) · 1.81 KB
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
import { payloadSchema } from './schema'
import { getEntityName } from 'contentful-batch-libs'
const attachEntityName = (details, payload) => {
details.map((detail) => {
if (detail.path.length >= 2) {
detail.entity = getEntityName(payload[detail.path[0]][detail.path[1]])
}
return detail
})
}
const countInvalidEntities = (validationData) => {
const entityCount = validationData.reduce((entities, currentDetail) => {
if (!entities[currentDetail.path[0]]) {
entities[currentDetail.path[0]] = 1
} else {
entities[currentDetail.path[0]]++
}
return entities
}, {})
return Object.keys(entityCount).map((key) => `${key}:${entityCount[key]}`)
}
const assertPayload = (payload) => {
const result = payloadSchema.validate(payload, { allowUnknown: true, abortEarly: false })
if (result.error) {
attachEntityName(result.error.details, payload)
const invalidEntityCount = countInvalidEntities(result.error.details).join(', ')
result.error.message = `${invalidEntityCount} - Get further details in the error log file`
delete result.error._original
throw result.error
}
}
const assertDefaultLocale = (source, destination) => {
const sourceDefaultLocale = source.locales.find((locale) => locale.default === true)
const destinationDefaultLocale = destination.locales.find((locale) => locale.default === true)
if (!sourceDefaultLocale || !destinationDefaultLocale) {
return
}
if (sourceDefaultLocale.code !== destinationDefaultLocale.code) {
throw new Error(`
Please make sure the destination space have the same default locale as the source\n
Default locale for source space : ${sourceDefaultLocale.code}\n
Default locale for destination space: ${destinationDefaultLocale.code}\n
`)
}
}
export {
assertPayload,
assertDefaultLocale
}