This repository has been archived by the owner on Dec 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathcreateNodeEntities.js
104 lines (97 loc) · 2.53 KB
/
createNodeEntities.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
const { isObject, flattenArray, isArray } = require('./utils/helpers')
const uuid = require('uuid/v1')
function getEntityNodeLinks (entities, nodeData) {
const links = {}
entities.forEach((entity) => {
const { name } = entity
const linkName = name + '___NODE'
if (links[linkName]) {
links[linkName] = isArray(links[linkName])
? [...links[linkName], entity.id]
: [links[linkName], entity.id]
// check if node-content is an array.
// if so, make the link also an array, to avoid conflicts,
// when you have node-content-arrays with just one element
} else if (isArray(nodeData[name])) {
links[linkName] = [entity.id]
} else {
links[linkName] = entity.id
}
})
return links
}
function getChildNodeKeys (data, schemas) {
if (!data) return []
return Object.keys(data).filter((key) => {
if (isObject(data[key])) return true
if (isArray(data[key]) && schemas[key]) {
return true
}
return false
})
}
function getDataWithoutChildEntities (data, childNodeKeys) {
const newData = { ...data }
childNodeKeys.forEach((key) => {
delete newData[key]
})
return newData
}
function buildEntity ({
name, data, schemas, createNodeId
}) {
const childNodeKeys = getChildNodeKeys(data, schemas)
const childEntities = flattenArray(
childNodeKeys.map(key => (
createNodeEntities({
name: key,
data: data[key],
schemas,
createNodeId
})
))
)
const dataWithoutChildEntities = getDataWithoutChildEntities(data, childNodeKeys)
const entityNodeLinks = getEntityNodeLinks(childEntities, data)
return [{
id: createNodeId(name + uuid()),
name,
data: dataWithoutChildEntities,
links: entityNodeLinks,
childEntities
}]
}
function normalizeData (name, data, schemas) {
const schema = schemas[name]
if (!data) return { dummy: true }
if (!Object.keys(data).length && !schema) {
return { dummy: true }
}
if (!schema) {
console.log(`Object '${name}': Better provide a schema!`)
}
return data
}
function createNodeEntities ({
name, data, createNodeId, schemas
}) {
if (isArray(data)) {
const entitiesArray = data.map(d => buildEntity({
name,
data: normalizeData(name, d, schemas),
schemas,
createNodeId
}))
return flattenArray(entitiesArray)
}
if (isObject(data)) {
return buildEntity({
name,
data: normalizeData(name, data, schemas),
schemas,
createNodeId
})
}
return []
}
module.exports = createNodeEntities