Edits history of script submission #22834 for ' New or Updated Page (confluence)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    import * as wmill from "windmill-client"
    
    /**
     * New or Updated Page
     * Emits pages created or updated since the last poll, tracked via Windmill state. Optionally restrict to a single space.
     */
    export async function main(auth: RT.Confluence, space_id: string | undefined) {
      const base = auth.baseUrl.replace(/\/$/, "")
      const lastChecked: number = (await wmill.getState()) ?? 0
    
      const path = space_id
        ? `/wiki/api/v2/spaces/${space_id}/pages`
        : `/wiki/api/v2/pages`
      const url = new URL(`${base}${path}`)
      url.searchParams.append("sort", "-modified-date")
      url.searchParams.append("limit", "50")
    
      const response = await fetch(url, {
        method: "GET",
        headers: {
          Authorization: "Basic " + btoa(`${auth.email}:${auth.apiToken}`),
          Accept: "application/json",
        },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const data = (await response.json()) as {
        results?: { version?: { createdAt?: string } }[]
      }
      const pages = data.results ?? []
    
      const ts = (p: { version?: { createdAt?: string } }) =>
        p.version?.createdAt ? Date.parse(p.version.createdAt) : 0
      const maxTs = pages.reduce((m, p) => Math.max(m, ts(p)), 0)
    
      // First run: set the watermark to the newest page seen and don't emit a backlog.
      if (!lastChecked) {
        if (maxTs) await wmill.setState(maxTs)
        return []
      }
    
      const fresh = pages
        .filter((p) => ts(p) > lastChecked)
        .sort((a, b) => ts(a) - ts(b))
    
      if (maxTs > lastChecked) {
        await wmill.setState(maxTs)
      }
    
      return fresh
    }
    

    Submitted by hugo989 4 hours ago