Edits history of script submission #24091 for ' List devices (ip_fabric)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    const DEFAULT_COLUMNS = [
      "id",
      "sn",
      "hostname",
      "siteName",
      "loginIp",
      "loginType",
      "vendor",
      "family",
      "platform",
      "model",
      "version",
      "devType",
      "uptime",
      "reload",
      "memoryUtilization",
    ]
    
    /**
     * List devices
     * 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).
     */
    export async function main(
      auth: RT.IpFabric,
      snapshot: string | undefined,
      columns: string[] | undefined,
      filters: { [key: string]: any } | undefined,
      sort_column: string | undefined,
      sort_order: "asc" | "desc" | undefined,
      limit: number | undefined,
      start: number | undefined
    ) {
      const pageLimit = limit || 100
      const pageStart = start || 0
    
      const payload: { [key: string]: any } = {
        columns: columns?.length ? columns : DEFAULT_COLUMNS,
        filters: filters ?? {},
        pagination: { limit: pageLimit, start: pageStart },
        // The SDK maps "$lastlocked" to the canonical "$lastLocked".
        snapshot:
          snapshot?.toLowerCase() === "$lastlocked"
            ? "$lastLocked"
            : snapshot || "$last",
      }
      if (sort_column) {
        payload.sort = { column: sort_column, order: sort_order || "asc" }
      }
    
      const version = (auth.api_version ?? "").trim()
      // Same normalization as the official SDK: "7.2" / "v7.2" -> v7.2, "7" -> v7.0.
      const match = version.match(/^v?(\d+)(?:\.(\d+))?/)
      if (version && !match) {
        throw new Error(
          `api_version "${version}" is not valid, use v#.# (e.g. v7.2)`
        )
      }
      const prefix = match ? `api/v${match[1]}.${match[2] ?? "0"}/` : "api/"
      const url = new URL(
        `${prefix}tables/inventory/devices`,
        auth.base_url.replace(/\/*$/, "/")
      )
    
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "X-API-Token": auth.token,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(payload),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const result = (await response.json()) as {
        data: { [key: string]: any }[]
        _meta: { [key: string]: any }
      }
      return {
        ...result,
        next_start:
          result.data.length === pageLimit ? pageStart + result.data.length : null,
      }
    }
    

    Submitted by hugo989 6 hours ago