Private/Helper/Invoke-BDWebRequest.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

function Invoke-BDWebRequest {
    [CmdletBinding(SupportsShouldProcess)]
    
    param (
        [Parameter(Mandatory = $true)] [ValidateSet('get', 'set', 'patch', 'post', 'delete')] $method, 
        [Parameter(Mandatory = $true)] [ValidateScript ( { Test-BDWebUri -address $_ })]$uri,
        [Parameter(Mandatory = $false )] [string] $body,
        [Parameter(Mandatory = $false )] $contentType = "application/json",
        [switch] $limitedOutput,
        [switch] $Raw,
        [switch] $Force
    )
    
    begin {
        if (-not $PSBoundParameters.ContainsKey('Verbose')) {
            $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')
        }
        if (-not $PSBoundParameters.ContainsKey('Confirm')) {
            $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')
        }
        if (-not $PSBoundParameters.ContainsKey('WhatIf')) {
            $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')
        }
    }
    
    process {
        Write-Verbose "method: $method"
        Write-Verbose "contentType: $contentType"

        if ($body) { Write-Verbose "body:$(ConvertTo-Json $body)" }

        if ($Force -or $PSCmdlet.ShouldProcess("$uri")) {
            $response = try {
                if ($body) {
                    (Invoke-WebRequest -Method $method -Uri $uri -ContentType $contentType -Headers @{Authorization = "Basic $($Session.User.EncodedCredential())" } -Body $body -UseBasicParsing -ErrorAction Stop)
                }
                else {
                    (Invoke-WebRequest -Method $method -Uri $uri -ContentType $contentType -Headers @{Authorization = "Basic $($Session.User.EncodedCredential())" } -UseBasicParsing -ErrorAction Stop)
                }
            }
            catch [System.Net.WebException] {
                Write-Verbose "An exception was caught: $($_.Exception.Message)"
                @{
                    BaseResponse = $_.Exception.Response
                    Exception    = $_
                }
            }

            Switch ($response.BaseResponse.StatusCode.Value__) {
                <#
                    200 OK
                    201 Created
                    202 Accepted
                    203 Non-Authoritative Information
                    204 No Content
                #>

                { $_ -in @(200, 201, 202, 203, 204) } {
                    if ($response.Content) {
                        $responseContent = ConvertFrom-Json $response.Content

                        if ($responseContent."@odata.context" -match '\$entity$') {
                            if (!$raw) { $responseContent.PSObject.properties.remove('@odata.context') }
                            return $responseContent
                        }
                        else {
                            $list = @()
                            $list += $responseContent.value
                            if (!$limitedOutput) {
                                if ($responseContent."@odata.nextLink") {
                                    $list += (Get-MSGObject $responseContent."@odata.nextLink")
                                }
                            }
                            return $list
                        }
                    }
                    else {
                        return @{ }
                    }
                }
                { $_ -in @(400) } {
                    $ErrorDetails = ConvertFrom-Json $response.Exception.ErrorDetails
                    throw [System.InvalidOperationException]::new("$($response.BaseResponse.StatusCode.Value__):: $($ErrorDetails.Error.Message)")
                }
                { $_ -in @(403) } {
                    $ErrorDetails = ConvertFrom-Json $response.Exception.ErrorDetails
                    throw [System.UnauthorizedAccessException]::new("$($response.BaseResponse.StatusCode.Value__):: $($ErrorDetails.Error.Message)")
                }
                { $_ -in @(404) } {
                    $ErrorDetails = ConvertFrom-Json $response.Exception.ErrorDetails
                    throw [System.Exception]::new("$($response.BaseResponse.StatusCode.Value__):: $($ErrorDetails.Error.Message)")
                }
                { $_ -in @(502) } {
                    #Invoke again?
                    Write-Verbose "Returned 502: Retrying call"
                    Start-Sleep -Milliseconds 250
                    return Invoke-BDWebRequest @PSBoundParameters
                }
                default {
                    throw "unexpected error $($response.BaseResponse.StatusCode.Value__)"
                }
            }
        }
    }
    
    end {
        
    }
}