forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-domain.js
More file actions
186 lines (166 loc) · 5.69 KB
/
Copy pathcreate-domain.js
File metadata and controls
186 lines (166 loc) · 5.69 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
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
import { GraphQLNonNull, GraphQLList, GraphQLID } from 'graphql'
import { mutationWithClientMutationId, fromGlobalId } from 'graphql-relay'
import { t } from '@lingui/macro'
import { Domain, Selectors } from '../../scalars'
import { domainType } from '../objects'
export const createDomain = new mutationWithClientMutationId({
name: 'CreateDomain',
description: 'Mutation used to create a new domain for an organization.',
inputFields: () => ({
orgId: {
type: GraphQLNonNull(GraphQLID),
description:
'The global id of the organization you wish to assign this domain to.',
},
domain: {
type: GraphQLNonNull(Domain),
description: 'Url that you would like to be added to the database.',
},
selectors: {
type: new GraphQLList(Selectors),
description: 'DKIM selector strings corresponding to this domain.',
},
}),
outputFields: () => ({
domain: {
type: domainType,
description: 'The newly created domain.',
resolve: async (payload) => {
return payload.domain
},
},
}),
mutateAndGetPayload: async (
args,
{
i18n,
request,
query,
collections,
transaction,
userKey,
auth: { checkPermission, userRequired },
loaders: { domainLoaderByDomain, orgLoaderByKey },
validators: { cleanseInput },
},
) => {
// Cleanse input
const { type: _orgType, id: orgId } = fromGlobalId(cleanseInput(args.orgId))
const domain = cleanseInput(args.domain)
let selectors
if (typeof args.selectors !== 'undefined') {
selectors = args.selectors.map((selector) => cleanseInput(selector))
} else {
selectors = []
}
// Get User
await userRequired()
// Check to see if org exists
const org = await orgLoaderByKey.load(orgId)
if (typeof org === 'undefined') {
console.warn(
`User: ${userKey} attempted to create a domain to an organization: ${orgId} that does not exist.`,
)
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
// Check to see if user belongs to org
const permission = await checkPermission({ orgId: org._id })
if (
permission !== 'user' &&
permission !== 'admin' &&
permission !== 'super_admin'
) {
console.warn(
`User: ${userKey} attempted to create a domain in: ${org.slug}, however they do not have permission to do so.`,
)
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
const insertDomain = {
domain: domain,
lastRan: null,
selectors: selectors,
}
// Check to see if domain already belongs to same org
let checkDomainCursor
try {
checkDomainCursor = await query`
LET domainIds = (FOR domain IN domains FILTER domain.domain == ${insertDomain.domain} RETURN { id: domain._id })
FOR domainId IN domainIds
LET domainEdges = (FOR v, e IN 1..1 ANY domainId.id claims RETURN { _from: e._from })
FOR domainEdge IN domainEdges
LET org = DOCUMENT(domainEdge._from)
FILTER org._key == ${org._key}
RETURN MERGE({ _id: org._id, _key: org._key, _rev: org._rev }, TRANSLATE(${request.language}, org.orgDetails))
`
} catch (err) {
console.error(
`Database error occurred while running check to see if domain already exists in an org: ${err}`,
)
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
const checkOrgDomain = await checkDomainCursor.next()
if (typeof checkOrgDomain !== 'undefined') {
console.warn(
`User: ${userKey} attempted to create a domain for: ${org.slug}, however that org already has that domain claimed.`,
)
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
// Check to see if domain already exists in db
const checkDomain = await domainLoaderByDomain.load(insertDomain.domain)
// Generate list of collections names
const collectionStrings = []
for (const property in collections) {
collectionStrings.push(property.toString())
}
// Setup Transaction
const trx = await transaction(collectionStrings)
if (typeof checkDomain === 'undefined') {
const insertedDomain = await trx.run(() =>
collections.domains.save(insertDomain),
)
await trx.run(() =>
collections.claims.save({ _from: org._id, _to: insertedDomain._id }),
)
} else {
const selectorList = checkDomain.selectors
selectors.forEach((selector) => {
if (!checkDomain.selectors.includes(selector)) {
selectorList.push(selector)
}
})
insertDomain.selectors = selectorList
await trx.run(
async () =>
await query`
UPSERT { _key: ${checkDomain._key} }
INSERT ${insertDomain}
UPDATE ${insertDomain}
IN domains
`,
)
await trx.run(() =>
collections.claims.save({ _from: org._id, _to: checkDomain._id }),
)
}
try {
await trx.commit()
} catch (err) {
console.error(
`Database error occurred while committing create domain transaction: ${err}`,
)
throw new Error(i18n._(t`Unable to create domain. Please try again.`))
}
// Clear dataloader incase anything was updated or inserted into domain
await domainLoaderByDomain.clear(insertDomain.domain)
const returnDomain = await domainLoaderByDomain.load(insertDomain.domain)
console.info(
`User: ${userKey} successfully created ${returnDomain.domain} in org: ${org.slug}.`,
)
returnDomain.id = returnDomain._key
return {
domain: {
...returnDomain,
},
}
},
})