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
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,64 @@ 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


Koa application is an instance of `EventEmitter` and emits following events to allow hooks into lifecycle.
All these events (except `error`) have `ctx` as first parameter:

### Event: 'request'

Emitted each time there is a request, with `ctx` as parameter, before passing to any middleware.
May be a good place for per-request context mutation, when needed, for example:

```js
app.on('request', ctx => {
ctx.state.start = Date.now();
// or something more advanced
if(!ctx.get('DNT')) ctx.state = new Proxy({})
})
```

### 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?


Emitted after passing all middleware, but before sending the response to network.
May be used when some action required to be latest after all middleware processing, for example:

```js
app.on('respond', ctx => {
if (ctx.state.start) ctx.set('X-Response-Time', Date.now() - ctx.state.start)
})
```

### Event: 'responded'

Emitted when the response stream is finished. Good place to cleanup any resources attached to `ctx.state` for example:

```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:
tinovyatkin marked this conversation as resolved.
Show resolved Hide resolved

```js
const onIdle10000ms = () => { console.warn('Server is idle for 10 seconds!'); }
const IDLE_INTERVAL = 10000;
let idleInterval = setInterval(onIdle10000ms, IDLE_INTERVAL);
app
.on('request', () => {
clearInterval(idleInterval);
})
.on('responded', () => {
idleInterval = setInterval(onIdle10000ms, IDLE_INTERVAL);
})
```

### Event: 'error'

See **Error Handling** below.

## Error Handling

By default outputs all errors to stderr unless `app.silent` is `true`.
Expand Down
11 changes: 9 additions & 2 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,15 @@ module.exports = class Application extends Emitter {
handleRequest(ctx, fnMiddleware) {
const res = ctx.res;
res.statusCode = 404;
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.emit('responded', ctx);
};
const handleResponse = () => {
this.emit('respond', ctx);
respond(ctx);
};
this.emit('request', ctx);
onFinished(res, onerror);
return fnMiddleware(ctx).then(handleResponse).catch(onerror);
}
Expand Down
73 changes: 73 additions & 0 deletions test/application/events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@

'use strict';

const assert = require('assert');
const Koa = require('../..');
const request = require('supertest');

describe('app emits events', () => {
it('should emit request, respond and responded once and in correct order', async() => {
const app = new Koa();
const emitted = [];
['request', 'respond', 'responded', 'error', 'customEvent'].forEach(event => app.on(event, () => emitted.push(event)));

app.use((ctx, next) => {
emitted.push('fistMiddleWare');
ctx.body = 'hello!';
return next();
});

app.use((ctx, next) => {
ctx.app.emit('customEvent');
return next();
});

app.use(ctx => {
emitted.push('lastMiddleware');
});

const server = app.listen();

let onceEvents = 0;
['request', 'respond', 'responded'].forEach(event =>
app.once(event, ctx => {
assert.strictEqual(ctx.app, app);
onceEvents++;
})
);

await request(server)
.get('/')
.expect(200);

assert.deepStrictEqual(emitted, ['request', 'fistMiddleWare', 'customEvent', 'lastMiddleware', 'respond', 'responded']);
assert.strictEqual(onceEvents, 3);
});

it('should emit error event on middleware throw', async() => {
const app = new Koa();
const emitted = [];
app.on('error', err => emitted.push(err));

app.use((ctx, next) => {
throw new TypeError('Hello Koa!');
});

const server = app.listen();

let onceEvents = 0;
app.once('error', (err, ctx) => {
assert.ok(err instanceof TypeError);
assert.strictEqual(ctx.app, app);
onceEvents++;
});

await request(server)
.get('/')
.expect(500);

assert.deepStrictEqual(emitted.length, 1);
assert.ok(emitted[0] instanceof TypeError);
assert.strictEqual(onceEvents, 1);
});
});