private/private-functions.ps1




function Confirm-PpsAccessToken {
    [CmdletBinding(DefaultParameterSetName='Default')]
    [Alias()]
    [OutputType([bool])]
    Param()

    if ($null -eq $script:PleasantConnection){
        throw [System.Security.Authentication.AuthenticationException]::New("Unauthenticated - Authenticate first with: Connect-Pps")
        return $false
    }
    elseif ($script:PleasantConnection.expires_at -le (Get-Date)){
        throw [System.Security.Authentication.AuthenticationException]::New("AccessToken Expired - Reauthenticate first with: Connect-Pps")
        return $false
    }
    elseif ( (-NOT [string]::IsNullOrEmpty($script:PleasantConnection.access_token)) -AND ($script:PleasantConnection.expires_at -gt (Get-Date)) ){
        return $true
    }
    else {
        Write-Output "Failed to check"
        return $false
    }    
}

function Invoke-PpsRestMethod {
    [CmdletBinding()]
    [Alias()]
    param (
        [ValidateNotNullOrEmpty()]
        [string]$Method,

        [ValidateNotNullOrEmpty()]
        [string]$EndPoint,

        [string]$Body,

        [string]$ContentType = 'application/json',

        [System.Collections.IDictionary]$Headers
    )
    begin {
        # Check if access token exists and is still valid
        if ((Confirm-PpsAccessToken)){
            $headers = @{
                "Accept" = "application/json"
                "Authorization" = $script:PleasantConnection.access_token
            }
        }
    }

    process {
        try {
            $splatParams = @{
                Uri         = $script:PleasantConnection.Server + '/' + $EndPoint.TrimStart('/')
                Headers     = $headers
                Method      = $Method
                ContentType = $ContentType
                ErrorAction = 'Stop'
            }
            if ($Body) {
                $splatParams['Body'] = [Text.Encoding]::UTF8.GetBytes($Body)
            }
            Invoke-RestMethod @splatParams
        }
        catch {
            throw $_
        }
    }
}