< Summary - Kestrun — Combined Coverage

Information
Class: Public.Route.Add-KrMapRoute
Assembly: Kestrun.PowerShell.Public
File(s): /home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Route/Add-KrMapRoute.ps1
Tag: Kestrun/Kestrun@9d3a582b2d63930269564a7591aa77ef297cadeb
Line coverage
58%
Covered lines: 29
Uncovered lines: 21
Coverable lines: 50
Total lines: 219
Line coverage: 58%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

File(s)

/home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Route/Add-KrMapRoute.ps1

#LineLine coverage
 1<#
 2    .SYNOPSIS
 3        Adds a new map route to the Kestrun server.
 4    .DESCRIPTION
 5        This function allows you to add a new map route to the Kestrun server by specifying the route path and the scrip
 6    .PARAMETER Server
 7        The Kestrun server instance to which the route will be added.
 8        If not specified, the function will attempt to resolve the current server context.
 9    .PARAMETER Options
 10        An instance of `Kestrun.Hosting.Options.MapRouteOptions` that contains the configuration for the route.
 11        This parameter is used to specify various options for the route, such as HTTP verbs, path, authorization schemes
 12    .PARAMETER Verbs
 13        The HTTP verbs (GET, POST, etc.) that the route should respond to.
 14    .PARAMETER Pattern
 15        The URL path for the new route.
 16    .PARAMETER ScriptBlock
 17        The script block to be executed when the route is accessed.
 18    .PARAMETER Code
 19        The code to be executed when the route is accessed, used in conjunction with the Language parameter.
 20    .PARAMETER Language
 21        The scripting language of the code to be executed.
 22    .PARAMETER CodeFilePath
 23        The file path to the code to be executed when the route is accessed.
 24    .PARAMETER AuthorizationSchema
 25        An optional array of authorization schemes that the route requires.
 26    .PARAMETER AuthorizationPolicy
 27        An optional array of authorization policies that the route requires.
 28    .PARAMETER ExtraImports
 29        An optional array of additional namespaces to import for the route.
 30    .PARAMETER ExtraRefs
 31        An optional array of additional assemblies to reference for the route.
 32    .PARAMETER AllowDuplicate
 33        If specified, allows the addition of duplicate routes with the same path and HTTP verb.
 34    .PARAMETER Arguments
 35        An optional hashtable of arguments to pass to the script block or code.
 36    .PARAMETER DuplicateAction
 37        Specifies the action to take if a duplicate route is detected. Options are 'Throw', 'Skip', 'Allow', or 'Warn'.
 38        Default is 'Throw', which will raise an error if a duplicate route is found.
 39    .PARAMETER PassThru
 40        If specified, the function will return the created route object.
 41    .OUTPUTS
 42        Returns the Kestrun server instance with the new route added.
 43    .EXAMPLE
 44        Add-KrMapRoute -Server $myServer -Path "/myroute" -ScriptBlock { Write-Host "Hello, World!" }
 45        Adds a new map route to the specified Kestrun server with the given path and script block.
 46    .EXAMPLE
 47
 48        Add-KrMapRoute -Server $myServer -Path "/myroute" -Code "Write-Host 'Hello, World!'" -Language PowerShell
 49        Adds a new map route to the specified Kestrun server with the given path and code.
 50    .EXAMPLE
 51        Get-KrServer | Add-KrMapRoute -Path "/myroute" -ScriptBlock { Write-Host "Hello, World!" } -PassThru
 52        Adds a new map route to the current Kestrun server and returns the route object.
 53    .NOTES
 54        This function is part of the Kestrun PowerShell module and is used to manage routes
 55#>
 56function Add-KrMapRoute {
 57    [KestrunRuntimeApi('Definition')]
 58    [CmdletBinding(defaultParameterSetName = 'ScriptBlock', PositionalBinding = $true)]
 59    [OutputType([Kestrun.Hosting.KestrunHost])]
 60    param(
 61        [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
 62        [Kestrun.Hosting.KestrunHost]$Server,
 63
 64        [Parameter(Mandatory = $true, ParameterSetName = 'Options', ValueFromPipeline = $true)]
 65        [Kestrun.Hosting.Options.MapRouteOptions]$Options,
 66
 67        [Parameter(ParameterSetName = 'ScriptBlock')]
 68        [Parameter(ParameterSetName = 'Code')]
 69        [Parameter(ParameterSetName = 'CodeFilePath')]
 170        [Kestrun.Utilities.HttpVerb[]]$Verbs = @([Kestrun.Utilities.HttpVerb]::Get),
 71
 72        [Parameter(ParameterSetName = 'ScriptBlock')]
 73        [Parameter(ParameterSetName = 'Code')]
 74        [Parameter(ParameterSetName = 'CodeFilePath')]
 75        [ValidatePattern('^/')]
 76        [alias('Path')]
 77        [string]$Pattern = '/',
 78
 79        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ScriptBlock')]
 80        [scriptblock]$ScriptBlock,
 81
 82        [Parameter(Mandatory = $true, ParameterSetName = 'Code')]
 83        [string]$Code,
 84
 85        [Parameter(Mandatory = $true, ParameterSetName = 'Code')]
 86        [Kestrun.Scripting.ScriptLanguage]$Language,
 87
 88        [Parameter(Mandatory = $true, ParameterSetName = 'CodeFilePath')]
 89        [string]$CodeFilePath,
 90
 91        [Parameter(ParameterSetName = 'ScriptBlock')]
 92        [Parameter(ParameterSetName = 'Code')]
 93        [Parameter(ParameterSetName = 'CodeFilePath')]
 94        [string[]]$AuthorizationSchema = $null,
 95
 96        [Parameter(ParameterSetName = 'ScriptBlock')]
 97        [Parameter(ParameterSetName = 'Code')]
 98        [Parameter(ParameterSetName = 'CodeFilePath')]
 99        [string[]]$AuthorizationPolicy = $null,
 100
 101        [Parameter(ParameterSetName = 'ScriptBlock')]
 102        [Parameter(ParameterSetName = 'Code')]
 103        [Parameter(ParameterSetName = 'CodeFilePath')]
 104        [string[]]$ExtraImports = $null,
 105
 106        [Parameter(ParameterSetName = 'ScriptBlock')]
 107        [Parameter(ParameterSetName = 'Code')]
 108        [Parameter(ParameterSetName = 'CodeFilePath')]
 109        [System.Reflection.Assembly[]]$ExtraRefs = $null,
 110
 111        [Parameter(ParameterSetName = 'ScriptBlock')]
 112        [Parameter(ParameterSetName = 'Code')]
 113        [Parameter(ParameterSetName = 'CodeFilePath')]
 114        [hashtable]$Arguments,
 115
 116        [Parameter()]
 117        [switch]$AllowDuplicate,
 118
 119        [Parameter()]
 120        [ValidateSet('Throw', 'Skip', 'Allow', 'Warn')]
 121        [string]$DuplicateAction = 'Throw',
 122
 123        [Parameter()]
 124        [switch]$PassThru
 125    )
 126    begin {
 127        # Ensure the server instance is resolved
 1128        $Server = Resolve-KestrunServer -Server $Server
 1129        if ($null -eq $Server) {
 0130            throw 'Server is not initialized. Please ensure the server is configured before setting options.'
 131        }
 132    }
 133    process {
 134
 1135        $exists = Test-KrRoute -Path $Pattern -Verb $Verbs
 136
 1137        if ($exists) {
 0138            if ($AllowDuplicate -or $DuplicateAction -eq 'Allow') {
 0139                Write-KrLog -Level Warning -Message "Route '{Path}' ({Verbs}) already exists; adding another." -Properti
 0140            } elseif ($DuplicateAction -eq 'Skip') {
 0141                Write-KrLog -Level Verbose -Message "Route '{Path}' ({Verbs}) exists; skipping." -Properties $Pattern, (
 142                return
 0143            } elseif ($DuplicateAction -eq 'Warn') {
 0144                Write-KrLog -Level Warning -Message "Route '{Path}' ({Verbs}) already exists." -Properties $Pattern, ($V
 145            } else {
 0146                throw [System.InvalidOperationException]::new(
 0147                    "Route '$Pattern' with method(s) $($Verbs -join ',') already exists.")
 148            }
 149        }
 150
 151        # -- if Options parameter is used, we can skip the rest of the parameters
 1152        if ($PSCmdlet.ParameterSetName -ne 'Options') {
 1153            $Options = [Kestrun.Hosting.Options.MapRouteOptions]::new()
 1154            $Options.HttpVerbs = $Verbs
 1155            $Options.Pattern = $Pattern
 1156            $Options.ExtraImports = $ExtraImports
 1157            $Options.ExtraRefs = $ExtraRefs
 1158            if ($null -ne $AuthorizationSchema) {
 1159                $Options.RequireSchemes = $AuthorizationSchema
 160            }
 1161            if ($null -ne $AuthorizationPolicy) {
 1162                $Options.RequirePolicies = $AuthorizationPolicy
 163            }
 164
 1165            if ($null -ne $Arguments) {
 1166                $dict = [System.Collections.Generic.Dictionary[string, object]]::new()
 1167                foreach ($key in $Arguments.Keys) {
 1168                    $dict[$key] = $Arguments[$key]
 169                }
 1170                $Options.Arguments = $dict
 171            }
 1172            switch ($PSCmdlet.ParameterSetName) {
 173                'ScriptBlock' {
 1174                    $Options.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 1175                    $Options.Code = $ScriptBlock.ToString()
 176                }
 177                'Code' {
 0178                    $Options.Language = $Language
 0179                    $Options.Code = $Code
 180                }
 181                'CodeFilePath' {
 0182                    if (-not (Test-Path -Path $CodeFilePath)) {
 0183                        throw "The specified code file path does not exist: $CodeFilePath"
 184                    }
 0185                    $extension = Split-Path -Path $CodeFilePath -Extension
 0186                    switch ($extension) {
 187                        '.ps1' {
 0188                            $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 189                        }
 190                        '.cs' {
 0191                            $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::CSharp
 192                        }
 193                        '.vb' {
 0194                            $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::VisualBasic
 195                        }
 196                        default {
 0197                            throw "Unsupported '$extension' code file extension."
 198                        }
 199                    }
 0200                    $Options.ValidateCodeSettings.Code = Get-Content -Path $CodeFilePath -Raw
 201                }
 202            }
 203        } else {
 1204            Write-Verbose 'Using provided MapRouteOptions instance.'
 205        }
 1206        if ($Server.RouteGroupStack.Count -gt 0) {
 1207            $grp = $Server.RouteGroupStack.Peek()
 1208            $Options = _KrMerge-MRO -Parent $grp -Child $Options
 209        }
 2210        [Kestrun.Hosting.KestrunHostMapExtensions]::AddMapRoute($Server, $Options) | Out-Null
 211
 1212        if ($PassThru.IsPresent) {
 213            # if the PassThru switch is specified, return the server instance
 214            # Return the modified server instance
 0215            return $Server
 216        }
 217    }
 218}
 219

Methods/Properties

Add-KrMapRoute()