Private/Submit-Request.ps1

function Submit-Request {
    <#
    .SYNOPSIS
        Sends a request to the Ghost Admin API and returns the parsed response.

    .DESCRIPTION
        Used by every public function. Adds the authentication headers, sends the body as UTF-8, converts the
        JSON response to objects and turns a failed request into an error with the message Ghost returned.

        A body is JSON, passed as -Body. An upload passes its form as bytes instead, with -Content and
        -ContentType.

        With -Paginate the request is repeated for every page of a browse endpoint and one response per page is
        returned. A request without a response body, such as a delete, returns nothing.

    .EXAMPLE
        Submit-Request -Uri $uri -Method $resources.Method -Body $body -Success $resources.Success

        Sends the request and returns the response as an object.
    #>

    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        # The full URI of the request, including the query string.
        [Parameter(Mandatory)]
        [string] $Uri,

        # The HTTP method.
        [Parameter(Mandatory)]
        [ValidateSet('Get', 'Post', 'Put', 'Delete')]
        [string] $Method,

        # The JSON body of the request.
        [string] $Body,

        # The body of a request that is not JSON, such as the form of an upload, as bytes. Needs -ContentType.
        [byte[]] $Content,

        # The content type of -Content, such as multipart/form-data with its boundary.
        [string] $ContentType,

        # The HTTP status code of a successful call. A warning is written when Ghost answers with another one.
        [int] $Success,

        # Retrieve every page of a browse endpoint. The URI must not contain limit or page.
        [switch] $Paginate
    )

    # The highest number of records Ghost returns in one page.
    $pageSize = 100

    # The progress bar of Invoke-WebRequest slows Windows PowerShell down considerably.
    $ProgressPreference = 'SilentlyContinue'

    $page = 1
    while ($page) {
        $requestUri = $Uri
        if ($Paginate) {
            $separator = if ($Uri.Contains('?')) { '&' } else { '?' }
            $requestUri = '{0}{1}limit={2}&page={3}' -f $Uri, $separator, $pageSize, $page
        }

        $request = @{
            Uri             = $requestUri
            Method          = $Method
            Headers         = Get-GhostHeader
            UseBasicParsing = $true
            ErrorAction     = 'Stop'
        }
        if ($Body) {
            # Bytes, because Windows PowerShell does not send a string body as UTF-8.
            $request['Body'] = [System.Text.Encoding]::UTF8.GetBytes($Body)
            $request['ContentType'] = 'application/json; charset=utf-8'
        }
        elseif ($Content) {
            $request['Body'] = $Content
            $request['ContentType'] = $ContentType
        }

        Write-Verbose -Message ('{0} {1}' -f $Method.ToUpperInvariant(), $requestUri)
        try {
            $response = Invoke-WebRequest @request
        }
        catch {
            throw (ConvertTo-GhostErrorRecord -ErrorRecord $_ -Method $Method -Uri $requestUri)
        }

        if ($Success -and $response.StatusCode -ne $Success) {
            Write-Warning -Message "Ghost answered with HTTP $($response.StatusCode) where $Success was expected."
        }

        # Without a text content type Windows PowerShell returns the content as bytes.
        $answer = $response.Content
        if ($answer -is [byte[]]) {
            $answer = [System.Text.Encoding]::UTF8.GetString($answer)
        }

        $result = $null
        if (-not [string]::IsNullOrWhiteSpace($answer)) {
            $result = ConvertFrom-Json -InputObject $answer
            $result
        }

        # Follow meta.pagination.next until Ghost reports there is no next page.
        $next = $null
        if ($Paginate -and $result -and $result.PSObject.Properties['meta']) {
            $meta = $result.meta
            if ($meta -and $meta.PSObject.Properties['pagination'] -and $meta.pagination) {
                $next = $meta.pagination.next
            }
        }
        $page = if ($next -and $next -gt $page) { $next } else { $null }
    }
}