Edits history of script submission #23986 for ' Get search results (splunk)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Get search results
     * Get one page of a finished search job's results as JSON. Page with count (default 100) and offset; pass next_offset back as offset until it is null (an empty page ends the results).
     */
    export async function main(
      auth: RT.Splunk,
      sid: string,
      count: number | undefined,
      offset: number | undefined,
      fields: string[] | undefined
    ) {
      const base = auth.base_url.replace(/\/+$/, "")
      const pageSize = count || 100
      const start = offset ?? 0
    
      const body = new URLSearchParams({
        output_mode: "json",
        count: String(pageSize),
        offset: String(start),
      })
      for (const f of fields ?? []) {
        if (f) body.append("f", f)
      }
    
      const response = await fetch(
        `${base}/services/search/v2/jobs/${encodeURIComponent(sid)}/results`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json",
          },
          body,
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      if (response.status === 204) {
        throw new Error(`204 results for job ${sid} are not available yet`)
      }
    
      const data = (await response.json()) as { results?: unknown[] }
      const returned = data.results?.length ?? 0
      return {
        ...data,
        count: pageSize,
        offset: start,
        // Like the Splunk SDK paginator: advance by the rows returned, stop on an
        // empty page (the server may cap count below the requested page size).
        next_offset: returned > 0 ? start + returned : null,
      }
    }
    

    Submitted by hugo989 3 hours ago