Skip to content

Commit

Permalink
Add routes integration for Express.js
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Oct 12, 2018
1 parent c4197ec commit d8e1844
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 17 deletions.
36 changes: 22 additions & 14 deletions examples/express/app.js
@@ -1,22 +1,30 @@
var express = require('express');
var AirbrakeClient = require('airbrake-js');
var makeErrorHandler = require('airbrake-js/dist/instrumentation/express');
var express = require('express')
var AirbrakeClient = require('airbrake-js')
var airbrakeExpress = require('airbrake-js/dist/instrumentation/express')

var app = express();

app.get('/', function hello (req, res) {
throw new Error('hello from Express');
res.send('Hello World!');
})
var app = express()

var airbrake = new AirbrakeClient({
projectId: 1,
projectKey: 'FIXME',
});
projectKey: 'FIXME'
})

// This middleware should be used before any routes are defined.
app.use(airbrakeExpress.makeMiddleware(airbrake))

app.get('/', function hello(req, res) {
throw new Error('hello from Express')
res.send('Hello World!')
})

app.get('/hello/:name', function hello(req, res) {
res.send(`Hello ${req.params.name}`)
})

// Error handler middleware should be the last one.
// See http://expressjs.com/en/guide/error-handling.html
app.use(makeErrorHandler(airbrake));
app.use(airbrakeExpress.makeErrorHandler(airbrake))

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
app.listen(3000, function() {
console.log('Example app listening on port 3000!')
})
15 changes: 13 additions & 2 deletions src/instrumentation/express.ts
@@ -1,7 +1,15 @@
import Notifier from '../notifier';
import Client from '../client';

function makeMiddleware(client: Client) {
return function(req, res, next): void {
let start = new Date();
next();
let ms = new Date().getTime() - start.getTime();
client.incRequest(req.method, req.route.path, res.statusCode, start, ms);
};
}

function makeErrorHandler(client: Notifier) {
function makeErrorHandler(client: Client) {
return function errorHandler(err: Error, req, _res, next): void {
let url = req.protocol + '://' + req.headers['host'] + req.path;
let notice: any = {
Expand All @@ -26,4 +34,7 @@ function makeErrorHandler(client: Notifier) {
};
}

(makeErrorHandler as any).makeMiddleware = makeMiddleware;
(makeErrorHandler as any).makeErrorHandler = makeErrorHandler;

export = makeErrorHandler;
2 changes: 1 addition & 1 deletion src/routes.ts
Expand Up @@ -65,7 +65,7 @@ export class Routes {
if (this.timer) {
return;
}
this.timer = setTimeout(() => { this.flush(); }, 1000);
this.timer = setTimeout(() => { this.flush(); }, 5000);
}

private flush() {
Expand Down

0 comments on commit d8e1844

Please sign in to comment.