Private/New-QueryString.ps1
|
function New-QueryString { <# .SYNOPSIS Adds the query string of a request to a URI. .DESCRIPTION Compares the query parameters an endpoint accepts, as defined in Get-GhostAPIData, with the parameters that were passed to the calling function. Every match is added to the URI, URL encoded, in alphabetical order so that the same call always produces the same URI. .EXAMPLE New-QueryString -Uri $uri -QueryKeys $resources.Query -Parameters $PSBoundParameters Returns the URI followed by, for example, ?include=authors%2Ctags&limit=5. #> [CmdletBinding()] [OutputType([string])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute( 'PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds a string. Nothing is changed on the system or on the site.' )] param( # The URI to add the query string to. [Parameter(Mandatory)] [string] $Uri, # The Query table of the endpoint: parameter name = name of the query string parameter. [System.Collections.IDictionary] $QueryKeys = @{}, # The parameters of the calling function, usually $PSBoundParameters. [System.Collections.IDictionary] $Parameters = @{} ) $pairs = foreach ($name in $QueryKeys.Keys | Sort-Object) { if ($Parameters.Keys -notcontains $name) { continue } $value = ConvertTo-ApiValue -Value $Parameters[$name] -AsString if ([string]::IsNullOrEmpty($value)) { continue } '{0}={1}' -f [uri]::EscapeDataString($QueryKeys[$name]), [uri]::EscapeDataString($value) } if (-not $pairs) { return $Uri } $separator = if ($Uri.Contains('?')) { '&' } else { '?' } $Uri + $separator + ($pairs -join '&') } |