Edits history of script submission #24123 for ' Get session (ixia_ixnetwork)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    // X-Api-Key header: the resource's api_key, or one obtained from username/password
    async function authHeaders(
      auth: RT.IxiaIxnetwork,
      base: string
    ): Promise<Record<string, string>> {
      if (auth.api_key) return { "X-Api-Key": auth.api_key }
      if (!auth.username) return {}
      const response = await fetch(`${base}/api/v1/auth/session`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({ username: auth.username, password: auth.password }),
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { apiKey } = (await response.json()) as { apiKey: string }
      return { "X-Api-Key": apiKey }
    }
    
    /**
     * Get session
     * Get one IxNetwork session by id, including its state and sub-state.
     */
    export async function main(auth: RT.IxiaIxnetwork, session_id: number) {
      const base = auth.base_url.replace(/\/+$/, "")
      const response = await fetch(`${base}/api/v1/sessions/${session_id}`, {
        headers: { ...(await authHeaders(auth, base)), Accept: "application/json" },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 6 hours ago