godaddy-dns.js
1.88 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
const GODADDY_DNS_API = 'https://api.godaddy.com/v3/domains/zones'
export async function setGodaddyARecord({ pat, zone, name, address, ttl }) {
const records = await listARecords({ pat, zone, name })
if (records.length === 1 && records[0].data === address && records[0].ttl === ttl) {
return { hostname: `${name}.${zone}`, action: 'kept', address }
}
for (const record of records) {
await godaddyRequest({
pat,
method: 'DELETE',
url: `${GODADDY_DNS_API}/${zone}/dns-records/${record.recordId}`,
body: null,
})
}
await godaddyRequest({
pat,
method: 'POST',
url: `${GODADDY_DNS_API}/${zone}/dns-records`,
body: { type: 'A', name, data: address, ttl },
})
let action = 'created'
if (records.length > 0) action = 'replaced'
return { hostname: `${name}.${zone}`, action, address }
}
async function listARecords({ pat, zone, name }) {
const url = new URL(`${GODADDY_DNS_API}/${zone}/dns-records`)
url.searchParams.set('type', 'A')
url.searchParams.set('name', name)
url.searchParams.set('pageSize', '100')
const response = await godaddyRequest({ pat, method: 'GET', url: url.href, body: null })
if (response === null || typeof response !== 'object' || !Array.isArray(response.items)) {
throw new Error(`GoDaddy DNS 响应缺少 items: ${name}.${zone}`)
}
return response.items
}
async function godaddyRequest({ pat, method, url, body }) {
const headers = { authorization: `Bearer ${pat}`, accept: 'application/json' }
const request = { method, headers }
if (body !== null) {
headers['content-type'] = 'application/json'
request.body = JSON.stringify(body)
}
const response = await fetch(url, request)
const text = await response.text()
if (!response.ok) {
throw new Error(`GoDaddy ${method} ${url} 返回 ${response.status}: ${text}`)
}
if (text.length === 0) return null
return JSON.parse(text)
}