emit more events
Koa extends EventEmitter but doesn't use that fact for anything apart of error event.
However, there are lifecycle hooks that have real-world use and otherwise hard to implement. This PR adds 3 events: 'request', 'respond' and 'responded' as well as documenting the fact that Application is an EventEmitter in a more clear way.
With these events is also quite possible to build reactive requests handling on base of Koa.
Codecov Report
Merging #1395 into master will decrease coverage by
0.20%. The diff coverage is100.00%.
@@ Coverage Diff @@
## master #1395 +/- ##
===========================================
- Coverage 100.00% 99.79% -0.21%
===========================================
Files 4 4
Lines 487 496 +9
Branches 136 137 +1
===========================================
+ Hits 487 495 +8
- Partials 0 1 +1
| Impacted Files | Coverage Δ | |
|---|---|---|
| lib/application.js | 100.00% <100.00%> (ø) |
|
| lib/context.js | 97.95% <0.00%> (-2.05%) |
:arrow_down: |
Continue to review full report at Codecov.
Legend - Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing dataPowered by Codecov. Last update 38cb591...bc62b2a. Read the comment docs.
all these events can implemented in application.handleRequest:
handleRequest(ctx, fnMiddleware) {
const res = ctx.res;
res.statusCode = 404;
const onerror = err => ctx.onerror(err);
const handleResponse = () => {
this.emit('respond', ctx);
respond(ctx);
}
onFinished(res, err => {
onerror(err);
this.emit('responded', ctx);
});
this.emit('request', ctx);
return fnMiddleware(ctx).then(handleResponse).catch(onerror);
}
And I'm not sure if we really need to add the respond event which will make people confuse, I'd like to keep request and responded(then rename responded to respond):
handleRequest(ctx, fnMiddleware) {
const res = ctx.res;
res.statusCode = 404;
const onerror = err => ctx.onerror(err);
const handleResponse = () => respond(ctx);
onFinished(res, err => {
onerror(err);
this.emit('respond', ctx);
});
this.emit('request', ctx);
return fnMiddleware(ctx).then(handleResponse).catch(onerror);
}
I would like to keep pre-send event ('respond' or if you suggest to rename it), as a good way to adjust context after all middleware but before sending to the network (there are some real world use for this event), don't see how it can be confusing while being documented, but if you have a rename suggestion - please do!
Yea, sorry, I read this wrong.
need test cases for this feature