Private/Invoke-SignApi.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
function Invoke-SignApi {
    [CmdletBinding()]
    param (
        #api path
        [string]
        $api,
        #request body
        [AllowEmptyCollection()]
        [System.Collections.Hashtable]
        $body = @{},
        [string]
        $method='GET',
        #save to file
        [string]
        $OutFile
    )

    begin {
        $apiuri = "$($script:siteinfo.url)$api"
        $header = @{
            "Authorization" = "Bearer $(ConvertFrom-SecureString -AsPlainText -SecureString $script:siteinfo.token )"
            "Accept" = "application/json"
        }

        $params = @{
            "Uri"       = $apiuri
            "Method"    = $method
            "Headers"   = $header
        }

        # convert non get request bodies to json
        # get-request as hastable
        # and file request as multipart/form-data
        if ($method -ne 'GET' -and $null -eq $body['file'] ) {
            [string]$body = [System.Collections.Hashtable]$body | ConvertTo-Json -Depth 7
            write-debug "Body: $body"
            $params['ContentType'] = 'application/json ;charset=utf-8'
            $params["Body"]      = $body
        } elseif ($method -eq 'GET') {
            $params["Body"]      = $body
        }else {
            $params["Form"]      = $body
        }


        if ($OutFile) {
            $params['OutFile'] = $OutFile
        }
    }

    process {


        Invoke-RestMethod @params

    }

    end {

    }
}