Skip to content

Commit

Permalink
feat: emit request and response event on app
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Jul 7, 2024
1 parent 2d787ea commit d5f08b4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,16 @@ export class Application extends Emitter {
* @private
*/
protected async handleRequest(ctx: ContextDelegation, fnMiddleware: (ctx: ContextDelegation) => Promise<void>) {
this.emit('request', ctx);
const res = ctx.res;
res.statusCode = 404;
const onerror = (err: any) => ctx.onerror(err);
onFinished(res, onerror);
onFinished(res, (err: any) => {
if (err) {
onerror(err);
}
this.emit('response', ctx);
});
try {
await fnMiddleware(ctx);
return this._respond(ctx);
Expand Down
31 changes: 30 additions & 1 deletion test/application/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import CreateError from 'http-errors';
import Koa from '../../src/index.js';

describe('app', () => {
// ignore test on Node.js v18
it('should handle socket errors', done => {
const app = new Koa();

Expand All @@ -25,6 +24,36 @@ describe('app', () => {
});
});

it('should emit request and response event', done => {
const app = new Koa();
let requestCount = 0;
let responseCount = 0;
app.on('request', ctx => {
assert.equal(ctx.url, '/');
requestCount++;
});
app.on('response', ctx => {
assert.equal(ctx.url, '/');
assert.equal(ctx.status, 404);
responseCount++;
if (responseCount === 2) {
assert.equal(requestCount, 2);
done();
}
});

request(app.callback())
.get('/')
.end(() => {
// empty
});
request(app.callback())
.get('/')
.end(() => {
// empty
});
});

it('should not .writeHead when !socket.writable', done => {
const app = new Koa();

Expand Down

0 comments on commit d5f08b4

Please sign in to comment.