Edits history of script submission #22833 for ' Update Page (confluence)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Update Page
     * Update a page's title, body, or status. The current version is fetched automatically and incremented; omitted fields keep their existing values.
     */
    export async function main(
      auth: RT.Confluence,
      page_id: string,
      title: string | undefined,
      body: string | undefined,
      status: "current" | "draft" | "archived" | undefined,
      representation: "storage" | "atlas_doc_format" | undefined,
      version_message: string | undefined
    ) {
      const base = auth.baseUrl.replace(/\/$/, "")
      const repr = representation ?? "storage"
      const authHeader = "Basic " + btoa(`${auth.email}:${auth.apiToken}`)
    
      // Fetch the current page to obtain the version number and any fields not being changed.
      const currentRes = await fetch(
        `${base}/wiki/api/v2/pages/${page_id}?body-format=${repr}`,
        {
          method: "GET",
          headers: { Authorization: authHeader, Accept: "application/json" },
        }
      )
      if (!currentRes.ok) {
        throw new Error(`${currentRes.status} ${await currentRes.text()}`)
      }
      const current = (await currentRes.json()) as {
        title: string
        status: string
        version: { number: number }
        body?: { [key: string]: { value?: string } }
      }
    
      const payload = {
        id: page_id,
        status: status ?? current.status,
        title: title ?? current.title,
        body: {
          representation: repr,
          value: body ?? current.body?.[repr]?.value ?? "",
        },
        version: {
          number: current.version.number + 1,
          message: version_message,
        },
      }
    
      const response = await fetch(`${base}/wiki/api/v2/pages/${page_id}`, {
        method: "PUT",
        headers: {
          Authorization: authHeader,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(payload),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 4 hours ago