forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-organizations-domains.js
More file actions
98 lines (87 loc) · 2.3 KB
/
Copy pathadd-organizations-domains.js
File metadata and controls
98 lines (87 loc) · 2.3 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
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
const {
checkOrganization,
createOrganization,
slugify,
checkDomain,
createDomain,
createClaim,
checkClaim,
} = require('./helpers')
const addOrganizationsDomains = async ({ db, query, data }) => {
const requiredCollectionTypes = {
claims: 'edge',
domains: 'document',
organizations: 'document',
affiliations: 'edge',
}
// check if collections exist
const existingCollections = (await db.listCollections()).map((collection) => {
return collection.name
})
for (const key of Object.keys(requiredCollectionTypes)) {
console.log(`Checking if collection "${key}" exists`)
if (!existingCollections.includes(key)) {
// collection does not exist, create collection
console.log(
`Collection "${key} does not exist, creating collection ${key}"`,
)
if (requiredCollectionTypes[key] === 'document') {
// create document collection
await db.createCollection(key)
} else {
// create edge collection
await db.createEdgeCollection(key)
}
} else {
// collections exists
console.log(`Collection "${key}" exists`)
}
}
for (const key in data) {
const trx = await db.beginTransaction(Object.keys(requiredCollectionTypes))
let org
org = await checkOrganization({ data, key, query })
if (!org) {
org = await createOrganization({ slugify, data, key, trx, query })
}
for (const domain of data[key].domains) {
const checkedDomain = await checkDomain({ query, domain })
if (!checkedDomain) {
const savedDomain = await createDomain({ trx, query, domain })
await createClaim({
trx,
query,
domainId: savedDomain._id,
orgId: org._id,
})
} else {
const claim = await checkClaim({
query,
domainId: checkedDomain._id,
orgId: org._id,
})
if (claim.length === 0) {
await createClaim({
trx,
query,
domainId: checkedDomain._id,
orgId: org._id,
})
}
}
console.log({
org: key,
domain,
saved: true,
})
}
try {
await trx.commit()
} catch (err) {
throw new Error(err)
}
}
}
module.exports = {
addOrganizationsDomains,
}