Private/Send-Request.ps1

<#
    .DESCRIPTION
    Wrapper for Nutanix API version 0.3.
 
    .NOTES
    Author: Timothy Rasiah
#>


function Send-Request {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact='High')]
    param (
        [Parameter(Mandatory=$true)]
        [ValidateSet("GET", "POST", "PUT", "DELETE")]
        [String]$method,
        [Parameter(Mandatory=$true)]
        [String]$endpoint,
        [Hashtable]$data = @{},
        [Hashtable]$headers = @{},
        [Hashtable]$params = @{}
    )

    if (!$Global:DefaultNutanixV3Connection) {
        Write-Error -Exception "You are not currently connected to a server. Please connect first using a Connect cmdlet."
        return
    }

    $url = "$($Global:DefaultNutanixV3Connection[0].BaseUrl)$($endpoint)"
    $querystring = foreach ($key in $params.Keys) { $key, $params[$key] -join '=' }
    $uri = if ($querystring) { "$($url)?$($querystring -join '&')" } else { $url }

    $headers["Authorization"] = "$($Global:DefaultNutanixV3Connection[0].BasicAuth)"
    $contenttype = "application/json"

    $body = $data | ConvertTo-Json -Compress -Depth 10

    switch ($method) {
        "GET" {
            $response = Invoke-RestMethod -Method $method -Uri $uri -Headers $headers -ContentType $contenttype -SkipCertificateCheck
        }
        "POST" {
            $response = Invoke-RestMethod -Method $method -Uri $uri -Headers $headers -Body $body -ContentType $contenttype -SkipCertificateCheck
        }
        "PUT" {
            $response = Invoke-RestMethod -Method $method -Uri $uri -Headers $headers -Body $body -ContentType $contenttype -SkipCertificateCheck
        }
        "DELETE" {
            $target = Invoke-RestMethod -Method "Get" -Uri $uri -Headers $headers -ContentType $contenttype -SkipCertificateCheck
            if ($target) {
                if ($PSCmdlet.ShouldProcess(($target | ConvertTo-Json -Depth 10 -Compress), "Delete")) {
                    $response = Invoke-RestMethod -Method $method -Uri $uri -Headers $headers -ContentType $contenttype -SkipCertificateCheck
                }
            }
        }
    }
    
    return $response
}