0

Update Blog Post

by
Published today

Update a blog post's title, body, or status. The current version is fetched automatically and incremented.

Script confluence Verified

The script

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

3
/**
4
 * Update Blog Post
5
 * Update a blog post's title, body, or status. The current version is fetched automatically and incremented; omitted fields keep their existing values.
6
 */
7
export async function main(
8
  auth: RT.Confluence,
9
  blog_post_id: string,
10
  title: string | undefined,
11
  body: string | undefined,
12
  status: "current" | "draft" | "archived" | undefined,
13
  representation: "storage" | "atlas_doc_format" | undefined,
14
  version_message: string | undefined
15
) {
16
  const base = auth.baseUrl.replace(/\/$/, "")
17
  const repr = representation ?? "storage"
18
  const authHeader = "Basic " + btoa(`${auth.email}:${auth.apiToken}`)
19

20
  // Fetch the current blog post to obtain the version number and any fields not being changed.
21
  const currentRes = await fetch(
22
    `${base}/wiki/api/v2/blogposts/${blog_post_id}?body-format=${repr}`,
23
    {
24
      method: "GET",
25
      headers: { Authorization: authHeader, Accept: "application/json" },
26
    }
27
  )
28
  if (!currentRes.ok) {
29
    throw new Error(`${currentRes.status} ${await currentRes.text()}`)
30
  }
31
  const current = (await currentRes.json()) as {
32
    title: string
33
    status: string
34
    version: { number: number }
35
    body?: { [key: string]: { value?: string } }
36
  }
37

38
  const payload = {
39
    id: blog_post_id,
40
    status: status ?? current.status,
41
    title: title ?? current.title,
42
    body: {
43
      representation: repr,
44
      value: body ?? current.body?.[repr]?.value ?? "",
45
    },
46
    version: {
47
      number: current.version.number + 1,
48
      message: version_message,
49
    },
50
  }
51

52
  const response = await fetch(
53
    `${base}/wiki/api/v2/blogposts/${blog_post_id}`,
54
    {
55
      method: "PUT",
56
      headers: {
57
        Authorization: authHeader,
58
        "Content-Type": "application/json",
59
        Accept: "application/json",
60
      },
61
      body: JSON.stringify(payload),
62
    }
63
  )
64

65
  if (!response.ok) {
66
    throw new Error(`${response.status} ${await response.text()}`)
67
  }
68

69
  return await response.json()
70
}
71