PowerShell / Polaris

A cross-platform, minimalist web framework for PowerShell
https://powershell.github.io/Polaris/
MIT License
512 stars 114 forks source link

Running Polaris from a Module exported function #178

Closed bgelens closed 5 years ago

bgelens commented 5 years ago

When wrapping Polaris in a function which is part of a module, Polaris instance won't be able to see the other Module functions (non exported) due to scoping issues. How would I solve this?

The idea is to wrap a fully functioning api as a Module so someone can just run Start-MyApi -Port 8080 without having to see a big script or any of the implementation details

Tiberriver256 commented 5 years ago

Hi bgelens,

Unfortunely using classes along with the Register-ObjectEvent leaves us with some oddities here. The action block of the Register-ObjectEvent doesn't execute within the scope of the module.

This is why we have to include this section and create the Polaris classes outside the module scope. https://github.com/PowerShell/Polaris/blob/a0117afb7308273d869167af2b3d8be4f5ed8fe4/Polaris.psd1#L48-L55

So the only option I have for you at the moment is to export all functions that are executed within a Polaris scriptblock (which is less than ideal for sure)

Thoughts on Polaris here

I've been thinking about the value we're actually adding by having it execute asynchronously (i.e. keeping the terminal active and allowing changes in scope to directly affect the running web server) and wondering if it isn't better to just leave that off as a feature and just having it either run synchronously or in jobs / runspaces which would mean functions would no longer have access to variables declared outside the function scope or explicitly passed to Polaris as a shared memory variable. @TylerLeonhardt.

Unless someone is aware of a PowerShell method for executing asynchronously that keeps all scoping intact (which would be epic!) I think those would be our best options.

Tiberriver256 commented 5 years ago

Relevant discussion in #127

bgelens commented 5 years ago

Thanks @Tiberriver256 for this great insight! I don't like the workaround (I had it parked it as last resort) but I can live with it for now.

My 2ct, I wouldn't mind if the terminal got locked, in my mind I wouldn't want to touch the PowerShell process that is hosting my app anyways. Plus, Wait-Debugger would work in that scenario as well right?

Tiberriver256 commented 5 years ago

Yeah, exactly. I'm going to close this one but feel free to weigh in on #127. I think we'll use that as our discussion on the asynchronous handling best future.