1 | |
2 |
|
3 | |
4 | * Get search results |
5 | * 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). |
6 | */ |
7 | export async function main( |
8 | auth: RT.Splunk, |
9 | sid: string, |
10 | count: number | undefined, |
11 | offset: number | undefined, |
12 | fields: string[] | undefined |
13 | ) { |
14 | const base = auth.base_url.replace(/\/+$/, "") |
15 | const pageSize = count || 100 |
16 | const start = offset ?? 0 |
17 |
|
18 | const body = new URLSearchParams({ |
19 | output_mode: "json", |
20 | count: String(pageSize), |
21 | offset: String(start), |
22 | }) |
23 | for (const f of fields ?? []) { |
24 | if (f) body.append("f", f) |
25 | } |
26 |
|
27 | const response = await fetch( |
28 | `${base}/services/search/v2/jobs/${encodeURIComponent(sid)}/results`, |
29 | { |
30 | method: "POST", |
31 | headers: { |
32 | Authorization: `Bearer ${auth.token}`, |
33 | "Content-Type": "application/x-www-form-urlencoded", |
34 | Accept: "application/json", |
35 | }, |
36 | body, |
37 | } |
38 | ) |
39 |
|
40 | if (!response.ok) { |
41 | throw new Error(`${response.status} ${await response.text()}`) |
42 | } |
43 |
|
44 | if (response.status === 204) { |
45 | throw new Error(`204 results for job ${sid} are not available yet`) |
46 | } |
47 |
|
48 | const data = (await response.json()) as { results?: unknown[] } |
49 | const returned = data.results?.length ?? 0 |
50 | return { |
51 | ...data, |
52 | count: pageSize, |
53 | offset: start, |
54 | |
55 | |
56 | next_offset: returned > 0 ? start + returned : null, |
57 | } |
58 | } |
59 |
|