0

Delete PTR record

Published today

Delete a PTR record identified by its _ref (from Search records). Returns the _ref of the deleted record.

Script infoblox_nios Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 2 hours ago
1
//native
2

3
function wapiUrl(auth: RT.InfobloxNios, path: string) {
4
  const host = auth.host
5
    .trim()
6
    .replace(/^https?:\/\//, "")
7
    .replace(/\/+$/, "")
8
  const version = auth.wapi_version.trim().replace(/^v/, "")
9
  return new URL(`https://${host}/wapi/v${version}/${path}`)
10
}
11

12
function refUrl(auth: RT.InfobloxNios, ref: string, type: string) {
13
  // Encode each segment so ?, # or .. in a ref can't reach another path or query.
14
  const segments = ref.split("/")
15
  if (
16
    segments[0] !== type ||
17
    segments.length < 2 ||
18
    segments.some((s) => s === "." || s === "..")
19
  ) {
20
    throw new Error(`Expected a ${type} reference, got: ${ref}`)
21
  }
22
  return wapiUrl(
23
    auth,
24
    segments.map((s) => encodeURIComponent(s).replace(/%3A/gi, ":")).join("/")
25
  )
26
}
27

28
function basicAuth(auth: RT.InfobloxNios) {
29
  const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`)
30
  return `Basic ${btoa(String.fromCharCode(...bytes))}`
31
}
32

33
async function wapiError(response: Response) {
34
  const text = await response.text()
35
  if (response.status === 401) {
36
    return new Error(
37
      "401 Unauthorized: wrong username or password, or the user's admin group has no API access"
38
    )
39
  }
40
  try {
41
    // WAPI errors are JSON: {"Error": "AdmConDataNotFoundError: ...", "code": "Client.Ibap.Data.NotFound", "text": "..."}
42
    const { Error: error, code, text: detail } = JSON.parse(text)
43
    if (error) {
44
      const message =
45
        detail && !error.includes(detail) ? `${error}: ${detail}` : error
46
      return new Error(
47
        `${response.status} ${message}${code ? ` (${code})` : ""}`
48
      )
49
    }
50
  } catch {}
51
  return new Error(`${response.status} ${text}`)
52
}
53

54
/**
55
 * Delete PTR record
56
 * Delete a PTR record identified by its _ref (from Search records). Returns the _ref of the deleted record.
57
 */
58
export async function main(auth: RT.InfobloxNios, ref: string) {
59
  const url = refUrl(auth, ref, "record:ptr")
60
  url.searchParams.append("_return_as_object", "1")
61

62
  const response = await fetch(url, {
63
    method: "DELETE",
64
    headers: {
65
      Authorization: basicAuth(auth),
66
      Accept: "application/json",
67
    },
68
  })
69

70
  if (!response.ok) {
71
    throw await wapiError(response)
72
  }
73

74
  return await response.json()
75
}
76