Edits history of script submission #23983 for ' Create search job (splunk)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create search job
     * Start an SPL search job and return its search ID (sid). A query that does not start with "search" or "|" gets "search " prepended, so a query starting with a macro that expands to a generating command needs its leading "|".
     */
    export async function main(
      auth: RT.Splunk,
      query: string,
      earliest_time: string | undefined,
      latest_time: string | undefined,
      exec_mode: "normal" | "blocking" | undefined
    ) {
      const base = auth.base_url.replace(/\/+$/, "")
      const trimmed = query.trim()
      // Keep queries that start with the search command (any case) or a generating
      // command ("| inputcsv"), else prepend "search ". Match the whole word: a
      // query like "search_id=*" is a field filter and still needs the prefix.
      const search = /^(search(\s|$)|\|)/i.test(trimmed)
        ? trimmed
        : `search ${trimmed}`
    
      const body = new URLSearchParams({ search, output_mode: "json" })
      if (earliest_time) body.append("earliest_time", earliest_time)
      if (latest_time) body.append("latest_time", latest_time)
      if (exec_mode) body.append("exec_mode", exec_mode)
    
      const response = await fetch(`${base}/services/search/jobs`, {
        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()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 3 hours ago