Polaris icon indicating copy to clipboard operation
Polaris copied to clipboard

[Question] how do I force the code to end the request before the end of the routine is reached?

Open loomanss opened this issue 5 years ago • 4 comments

i was assuming that if i use $response.send() the request is closed and the response is sent to the client. however, the code will continue to run. The result is that the last $ response.send is displayed as a result on the client side. how do I force the code to end the request before the end of the routine is reached?

my work-around at this moment :

Import-Module -Name Polaris
$global:PolarisRestPort = 8183
$global:AppName = "Polaris-Test"

    $app = Start-Polaris -Port $global:PolarisRestPort -MinRunspaces 1  -MaxRunspaces  5   # all params are optional

    $functionMiddleWare = {
        $authkey = $Request.Headers['Authorization']
        if($authkey -eq $null)
        { 
            $Response.SetStatusCode(401)
            $Response.Send("not authorized")
            [Polaris]::Send($Response)
            }}
    New-PolarisRouteMiddleware -Name MyParser -Polaris $app  -Scriptblock $functionMiddleWare
    $functionHello = { $Response.Send("hello")}
    New-PolarisRoute -method GET -Path '/hello' -Polaris $app  -Scriptblock $functionHello
    while($app.Listener.IsListening){Wait-Event callbackcomplete}

loomanss avatar Sep 20 '19 08:09 loomanss

If you want to return early in a handler, couldn't you use a return after $Response.Send(?

TylerLeonhardt avatar Sep 20 '19 14:09 TylerLeonhardt

seems not to work for me:

  $functionMiddleWare = {
        $authkey = $Request.Headers['Authorization']
        if($authkey -eq $null)
        { 
            $Response.SetStatusCode(401)
            $Response.Send("not authorized")
            return
            }}

loomanss avatar Sep 20 '19 17:09 loomanss

Hey @loomanss - The return statement would work from a standard route but from a middleware I believe you are going to need the changes I introduced in #192.

Not sure how long before we can get the code out to the gallery as a new version but you could always just download the module from this repo and try it out to make sure it works for you.

With the latest changes you can just do:

$functionMiddleWare = {
        $authkey = $Request.Headers['Authorization']
        if($authkey -eq $null)
        { 
            $Response.SetStatusCode(401)
            $Response.Send("not authorized")
            }}

There's more details on custom authentication in the about_Authentication.md document

Tiberriver256 avatar Sep 20 '19 18:09 Tiberriver256

Yes - sorry for the delay. Drowning in releases I need to do at the moment 😅

TylerLeonhardt avatar Sep 21 '19 01:09 TylerLeonhardt