PowerShell/Polaris

Any way to share state between route handlers?

Closed this issue ยท 3 comments

vors commented

I'm looking for a way to create few related endpoints.
I would be good to be able to share some objects between them.

For example, that could work in theory

$global:foo = 444
New-PostRoute -Path "/foo" -ScriptBlock {
    param($request,$response)                                                                        $response.Send("foo = " +  $global:foo)
}

Such is the downside of using a runspace pool - no shared state. That said, with #49 middleware could be used to share state.

# New middleware command - will get run before every route script block gets executed
New-RouteMiddleware -Name SetupGlobalFoo -ScriptBlock {
    $global:foo = 444
}

# note the removal of the param! Breaking change in latest PR
New-PostRoute -Path "/foo" -ScriptBlock {
    $response.Send("foo = " +  $global:foo)
}
New-PostRoute -Path "/bar" -ScriptBlock {
    $response.Send("foo = " +  $global:foo)
}

Is it the ideal situation? Not yet - but it's something for now. I'm toying with the idea of taking all $global:* vars and loading them in a middleware.

Middleware just got merged in - still need to update docs and whatnot. Docs are coming though :)

vors commented

Hm, I think it would be good to have a switch, maybe on Start-Polaris to load all vars.
We did something similar for Invoke-Parallel.
It's the same story: we want to benefit from a thread pool, but it should be brain-dead to use. Ideally, a drop-in replacement that can immediately use the code that user already wrote.

In the invoke-parallel case, the goal was to go from 1..100 | % {...} to 1..100 | <something> (...) where the {...} would not need to change. Then it's very easy to adopt when user realize that they will benefit from parallelism. Compare it with the PS job for parallelization: you need to marshall all arguments and write a fair amount of code to achieve it.
So this is a very inefficient switch, but it sure saves time and that's what needed for quick iterations. And that sure should not be the default.

This should work now since we are using Register-ObjectEvent and share the runspace ๐Ÿ˜ƒ