-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathdomain.js
62 lines (58 loc) · 1.86 KB
/
domain.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
import { validateSchema, customDomainSchema } from '@/lib/validate'
import { GqlAuthenticationError, GqlInputError } from '@/lib/error'
import { randomBytes } from 'node:crypto'
export default {
Query: {
customDomain: async (parent, { subName }, { models }) => {
return models.customDomain.findUnique({ where: { subName } })
}
},
Mutation: {
setCustomDomain: async (parent, { subName, domain }, { me, models }) => {
if (!me) {
throw new GqlAuthenticationError()
}
const sub = await models.sub.findUnique({ where: { name: subName } })
if (!sub) {
throw new GqlInputError('sub not found')
}
if (sub.userId !== me.id) {
throw new GqlInputError('you do not own this sub')
}
domain = domain.trim() // protect against trailing spaces
if (domain && !validateSchema(customDomainSchema, { domain })) {
throw new GqlInputError('Invalid domain format')
}
if (domain) {
const existing = await models.customDomain.findUnique({ where: { subName } })
if (existing && existing.domain === domain) {
throw new GqlInputError('domain already set')
}
return await models.customDomain.upsert({
where: { subName },
update: {
domain,
dnsState: 'PENDING',
sslState: 'WAITING',
certificateArn: null
},
create: {
domain,
dnsState: 'PENDING',
verificationTxt: randomBytes(32).toString('base64'),
sub: {
connect: { name: subName }
}
}
})
} else {
try {
return await models.customDomain.delete({ where: { subName } })
} catch (error) {
console.error(error)
throw new GqlInputError('failed to delete domain')
}
}
}
}
}