1 | |
2 |
|
3 | const DEFAULT_COLUMNS = [ |
4 | "id", |
5 | "sn", |
6 | "hostname", |
7 | "siteName", |
8 | "loginIp", |
9 | "loginType", |
10 | "vendor", |
11 | "family", |
12 | "platform", |
13 | "model", |
14 | "version", |
15 | "devType", |
16 | "uptime", |
17 | "reload", |
18 | "memoryUtilization", |
19 | ] |
20 |
|
21 | |
22 | * List devices |
23 | * List one page of the device inventory (tables/inventory/devices) of a snapshot. Filters use the table filter syntax, e.g. {"vendor": ["like", "cisco"]}. Returns the rows, the table metadata and next_start (null on the last page). |
24 | */ |
25 | export async function main( |
26 | auth: RT.IpFabric, |
27 | snapshot: string | undefined, |
28 | columns: string[] | undefined, |
29 | filters: { [key: string]: any } | undefined, |
30 | sort_column: string | undefined, |
31 | sort_order: "asc" | "desc" | undefined, |
32 | limit: number | undefined, |
33 | start: number | undefined |
34 | ) { |
35 | const pageLimit = limit || 100 |
36 | const pageStart = start || 0 |
37 |
|
38 | const payload: { [key: string]: any } = { |
39 | columns: columns?.length ? columns : DEFAULT_COLUMNS, |
40 | filters: filters ?? {}, |
41 | pagination: { limit: pageLimit, start: pageStart }, |
42 | |
43 | snapshot: |
44 | snapshot?.toLowerCase() === "$lastlocked" |
45 | ? "$lastLocked" |
46 | : snapshot || "$last", |
47 | } |
48 | if (sort_column) { |
49 | payload.sort = { column: sort_column, order: sort_order || "asc" } |
50 | } |
51 |
|
52 | const version = (auth.api_version ?? "").trim() |
53 | |
54 | const match = version.match(/^v?(\d+)(?:\.(\d+))?/) |
55 | if (version && !match) { |
56 | throw new Error( |
57 | `api_version "${version}" is not valid, use v#.# (e.g. v7.2)` |
58 | ) |
59 | } |
60 | const prefix = match ? `api/v${match[1]}.${match[2] ?? "0"}/` : "api/" |
61 | const url = new URL( |
62 | `${prefix}tables/inventory/devices`, |
63 | auth.base_url.replace(/\/*$/, "/") |
64 | ) |
65 |
|
66 | const response = await fetch(url, { |
67 | method: "POST", |
68 | headers: { |
69 | "X-API-Token": auth.token, |
70 | "Content-Type": "application/json", |
71 | Accept: "application/json", |
72 | }, |
73 | body: JSON.stringify(payload), |
74 | }) |
75 |
|
76 | if (!response.ok) { |
77 | throw new Error(`${response.status} ${await response.text()}`) |
78 | } |
79 |
|
80 | const result = (await response.json()) as { |
81 | data: { [key: string]: any }[] |
82 | _meta: { [key: string]: any } |
83 | } |
84 | return { |
85 | ...result, |
86 | next_start: |
87 | result.data.length === pageLimit ? pageStart + result.data.length : null, |
88 | } |
89 | } |
90 |
|