-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
initialize context.state
sooner
#1646
Comments
I like to see |
If you want some info on every request, you should just modify context as you described. Changing app.context.state type and/or its behaviour would be a pretty significant semver breakage though. Edit: I see, I read this a bit too fast before responding. Though I'm not as involved anymore so I have no strong opinions about this. |
So after having slept on this I think a PR that makes context creation an overridable Koa option is the way to go. If anyone wants to take a stab at this it would be welcome. |
Hi, I would like to work on this issue. |
I am wondering if there is a development guide for contributors somewhere in the repo? |
this has not being solved yet, i ran into this today |
Reading my initial issue again, I'd actually recommend using |
@dwhieb The change does not work |
|
Expected Behavior
If there's information I want to be available in every request, I'd like to be able to specify that information when I initialize the app, using
app.context.state
, like so:Best practice for Koa is to use
context.state
to pass information through middleware, and to useapp.context
add properties used throughout the app, so this seems like the right approach. It's also parallel to the way that I can setapp.locals
in an Express app to make that information available tores.locals
.Actual Behavior
The above code snippet throws a TypeError because
context.state
isn't initialized until the app receives a request, here:koa/lib/application.js
Lines 168 to 181 in aa816ca
The following also doesn't work, because the
state
property gets overridden by the code linked above:Suggested Solution
Add the
state
property to the context prototype instead of initializing it when a request comes in. Then, inapp.createContext()
, create a newstate
object that only lives for the lifetime of the request, usingapp.context.state
as its prototype.Replace:
koa/lib/application.js
Line 179 in aa816ca
with:
Workaround
The workaround is to add the information directly to
app.context
rather thanapp.context.state
. However, this is undesirable because it goes against the best practice of usingcontext.state
to encapsulate state.I'd be happy to open a PR for this if it's a change you'd like implemented.
The text was updated successfully, but these errors were encountered: