Skip to content
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

emit more events #1395

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open

emit more events #1395

wants to merge 19 commits into from

Conversation

tinovyatkin
Copy link
Contributor

@tinovyatkin tinovyatkin commented Oct 13, 2019

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
Copy link

codecov bot commented Oct 13, 2019

Codecov Report

Merging #1395 into master will decrease coverage by 0.20%.
The diff coverage is 100.00%.

Impacted file tree graph

@@             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%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 38cb591...bc62b2a. Read the comment docs.

@dead-horse
Copy link
Member

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);
  }

@tinovyatkin tinovyatkin mentioned this pull request Oct 15, 2019
@tinovyatkin
Copy link
Contributor Author

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!

@fl0w
Copy link
Contributor

fl0w commented Oct 15, 2019

Yea, sorry, I read this wrong.

lib/application.js Outdated Show resolved Hide resolved
@dead-horse
Copy link
Member

need test cases for this feature

const onerror = err => ctx.onerror(err);
const handleResponse = () => respond(ctx);
const onerror = err => {
if (null != err) ctx.onerror(err);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is breaking change.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does it breaks?!

this.once(responding, () => this.emit('respond', ctx));

const onerror = err => {
if (null != err) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the old code will execute onerror no matter the err is null or not. So I think this is a breaking change.

Copy link
Contributor Author

@tinovyatkin tinovyatkin Oct 19, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fengmk2 onerror in current implementation just returns immediately if err is null, so, nothing breaks here actually.

@@ -221,6 +221,68 @@ Note:
- Many properties on `ctx` are defined using getters, setters, and `Object.defineProperty()`. You can only edit these properties (not recommended) by using `Object.defineProperty()` on `app.context`. See https://github.com/koajs/koa/issues/652.
- Mounted apps currently use their parent's `ctx` and settings. Thus, mounted apps are really just groups of middleware.

## Events
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for this doc, very useful for a PR

})
```

### Event: 'respond'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't see how this or the request event have any benefit over regular middleware

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it actually has less benefit because you cannot use async functions

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no need to have advantage or disadvantage and not always sync call is inferior to async call from application point of view. If you follow Node.JS core development strategy then you certainly will notice “mix and match” innovation in handling async flow - once was added into events core module, finished, Readable.from(AsyncIterator), and Readable[AsyncIterator] into the stream - so, modern Node.JS is inviting to pick events, streams or Promises whatever solves problem more efficiently OR USE THEM ALTOGETHER. If Koa is the EventEmitter why it doesn’t emit any lifecycle events apart of error and why event handlers should be considered inferior?

})
```

Note: `respond` event may not be emitted in case of premature socket close (due to a middleware timeout, for example).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exceptions like this make it less useful and more difficult to maintain

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not an exception - it's a logic of this event because the response in this case never happened.


```js
app.on('responded', ctx => {
if (ctx.state.dataStream) ctx.state.dataStream.destroy();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't understand this use-case. clean up callbacks on streams should be handled when you create and pipe them.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How would you know from the stream that, for example, connection with a client was prematurely lost and not the whole stream was consumed?

More advanced example, use events to detect that server is idling for some time:

```js
const server = app.listen();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i would actually recommend not doing this in koa. i would do this as a req/res decorator:

const fn = app.callback()

const checkIdle = (fn) => (req, res) => {
  // do stuff
  return fn(req, res)
}

http.createServer(checkIdle(fn))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I probably missing something here as I’m struggling to understand: if you created Koa as an extension of EventEmitter in the first place, why do you consider using events is antipattern and inferior to writing low-level decorator here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants