Skip to content

Commit

Permalink
feat: emit request and response event (#2020)
Browse files Browse the repository at this point in the history
  • Loading branch information
dead-horse authored Jan 26, 2018
1 parent ddbb4b3 commit 22dfaa7
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const fs = require('fs');
const graceful = require('graceful');
const http = require('http');
const cluster = require('cluster-client');
const onFinished = require('on-finished');
const { assign } = require('utility');
const eggUtils = require('egg-core').utils;
const EggApplication = require('./egg');
Expand Down Expand Up @@ -145,6 +146,12 @@ class Application extends EggApplication {
return context;
}

handleRequest(ctx, fnMiddleware) {
this.emit('request', ctx);
super.handleRequest(ctx, fnMiddleware);
onFinished(ctx.res, () => this.emit('response', ctx));
}

/**
* save routers to `run/router.json`
* @private
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"koa-is-json": "^1.0.0",
"koa-override": "^3.0.0",
"mime-types": "^2.1.17",
"on-finished": "^2.3.0",
"sendmessage": "^1.1.0",
"urllib": "^2.25.1",
"utility": "^1.13.1",
Expand Down
34 changes: 34 additions & 0 deletions test/lib/application.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const mm = require('egg-mock');
const sleep = require('mz-modules/sleep');
const fs = require('fs');
const path = require('path');
const pedding = require('pedding');
const Application = require('../../lib/application');
const utils = require('../utils');

Expand Down Expand Up @@ -216,5 +217,38 @@ describe('test/lib/application.test.js', () => {
app.emit('cookieLimitExceed', { name: 'name', value: 'value', ctx });
});
});

describe('request and response event', () => {
it('should emit when request success', done => {
done = pedding(done, 3);
app.once('request', ctx => {
assert(ctx.path === '/class-controller');
done();
});
app.once('response', ctx => {
assert(ctx.status === 200);
done();
});
app.httpRequest()
.get('/class-controller')
.expect('this is bar!')
.expect(200, done);
});

it('should emit when request error', done => {
done = pedding(done, 3);
app.once('request', ctx => {
assert(ctx.path === '/obj-error');
done();
});
app.once('response', ctx => {
assert(ctx.status === 500);
done();
});
app.httpRequest()
.get('/obj-error')
.expect(500, done);
});
});
});
});

0 comments on commit 22dfaa7

Please sign in to comment.