Merge pull request #1433 from jedmao/fix-express

More specific Express types
This commit is contained in:
Basarat Ali Syed
2013-12-12 14:12:18 -08:00
2 changed files with 156 additions and 160 deletions
+131 -132
View File
@@ -20,7 +20,7 @@ app.use(express.session());
// Session-persisted message middleware
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response, next) => {
var err = req.session.error
, msg = req.session.success;
delete req.session.error;
@@ -40,7 +40,7 @@ var users = <any>{
// when you create a user, generate a salt
// and hash the password ('foobar' is the pass here)
hash('foobar', function (err, salt, hash) {
hash('foobar', (err, salt, hash) => {
if (err) throw err;
// store the salt & hash in the "db"
users.tj.salt = salt;
@@ -58,11 +58,11 @@ function authenticate(name, pass, fn) {
// apply the same algorithm to the POSTed password, applying
// the hash against the pass / salt, if there is a match we
// found the user
hash(pass, user.salt, function (err, hash) {
hash(pass, user.salt, (err, hash) => {
if (err) return fn(err);
if (hash == user.hash) return fn(null, user);
fn(new Error('invalid password'));
})
});
}
function restrict(req: express.Request, res: express.Response, next?: Function) {
@@ -74,32 +74,32 @@ function restrict(req: express.Request, res: express.Response, next?: Function)
}
}
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.redirect('login');
});
app.get('/restricted', restrict, function (req, res) {
app.get('/restricted', restrict, (req: express.Request, res: express.Response) => {
res.send('Wahoo! restricted area, click to <a href="/logout">logout</a>');
});
app.get('/logout', function (req, res) {
app.get('/logout', (req: express.Request, res: express.Response) => {
// destroy the user's session to log them out
// will be re-created next request
req.session.destroy(function () {
req.session.destroy(() => {
res.redirect('/');
});
});
app.get('/login', function (req, res) {
app.get('/login', (req: express.Request, res: express.Response) => {
res.render('login');
});
app.post('/login', function (req, res) {
authenticate(req.body.username, req.body.password, function (err, user) {
app.post('/login', (req: express.Request, res: express.Response) => {
authenticate(req.body.username, req.body.password, (err, user) => {
if (user) {
// Regenerate session when signing in
// to prevent fixation
req.session.regenerate(function () {
req.session.regenerate(() => {
// Store the user's primary key
// in the session store to be retrieved,
// or in this case the entire user object
@@ -139,7 +139,7 @@ while (n--) {
app.use(express.logger('dev'));
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.render('pets', { pets: pets });
});
@@ -148,24 +148,24 @@ console.log('Express listening on port 3000');
/////////////
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.format({
html: function () {
res.send('<ul>' + users.map(function (user) {
html: () => {
res.send('<ul>' + users.map(user => {
return '<li>' + user.name + '</li>';
}).join('') + '</ul>');
},
text: function () {
res.send(users.map(function (user) {
text: () => {
res.send(users.map(user => {
return ' - ' + user.name + '\n';
}).join(''));
},
json: function () {
json: () => {
res.json(users);
}
})
});
});
// or you could write a tiny middleware like
@@ -173,9 +173,9 @@ app.get('/', function (req, res) {
function format(mod) {
var obj = require(mod);
return function (req, res) {
return (req: express.Request, res: express.Response) => {
res.format(obj);
}
};
}
app.get('/users', format('./users'));
@@ -207,7 +207,7 @@ app.use(express.cookieParser('my secret here'));
// parses json, x-www-form-urlencoded, and multipart/form-data
app.use(express.bodyParser());
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
if (req.cookies.remember) {
res.send('Remembered :). Click to <a href="/forget">forget</a>!.');
} else {
@@ -217,12 +217,12 @@ app.get('/', function (req, res) {
}
});
app.get('/forget', function (req, res) {
app.get('/forget', (req: express.Request, res: express.Response) => {
res.clearCookie('remember');
res.redirect('back');
});
app.post('/', function (req, res) {
app.post('/', (req: express.Request, res: express.Response) => {
var minute = 60000;
if (req.body.remember) res.cookie('remember', 1, { maxAge: minute });
res.redirect('back');
@@ -248,7 +248,7 @@ app.use(express.cookieSession());
app.use(count);
// custom middleware
function count(req, res) {
function count(req: express.Request, res: express.Response) {
req.session.count = req.session.count || 0;
var n = req.session.count++;
res.send('viewed ' + n + ' times\n');
@@ -274,7 +274,7 @@ api.use(express.bodyParser());
* CORS support.
*/
api.all('*', function (req, res, next) {
api.all('*', (req: express.Request, res: express.Response, next) => {
if (!req.get('Origin')) return next();
// use "*" here to accept any origin
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
@@ -289,7 +289,7 @@ api.all('*', function (req, res, next) {
* POST a user.
*/
api.post('/user', function (req, res) {
api.post('/user', (req: express.Request, res: express.Response) => {
console.log(req.body);
res.send(201);
});
@@ -302,7 +302,7 @@ console.log('api listening on 3001');
////////////////////
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.send('<ul>'
+ '<li>Download <a href="/files/amazing.txt">amazing.txt</a>.</li>'
+ '<li>Download <a href="/files/missing.txt">missing.txt</a>.</li>'
@@ -311,7 +311,7 @@ app.get('/', function (req, res) {
// /files/* is accessed via req.params[0]
// but here we name it :file
app.get('/files/:file(*)', function (req, res, next?) {
app.get('/files/:file(*)', (req: express.Request, res: express.Response) => {
var file = req.params.file
, path = __dirname + '/files/' + file;
@@ -322,7 +322,7 @@ app.get('/files/:file(*)', function (req, res, next?) {
// below our routes, you will be able to
// "intercept" errors, otherwise Connect
// will respond with 500 "Internal Server Error".
app.use(function (err, req, res, next) {
app.use((err, req, res: express.Response, next) => {
// special-case 404s,
// remember you could
// render a 404 template here
@@ -363,7 +363,7 @@ app.set('views', __dirname + '/views');
// ex: res.render('users.html').
app.set('view engine', 'html');
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.render('users', {
users: users,
title: "EJS example",
@@ -390,12 +390,12 @@ app.use(app.router);
app.use(error);
// error handling middleware have an arity of 4
// instead of the typical (req, res, next),
// instead of the typical (req: express.Request, res: express.Response, next),
// otherwise they behave exactly like regular
// middleware, you may have several of them,
// in different orders etc.
function error(err, req, res, next) {
function error(err, req, res: express.Response, next) {
// log it
if (!test) console.error(err.stack);
@@ -403,14 +403,14 @@ function error(err, req, res, next) {
res.send(500);
}
app.get('/', function (req, res) {
app.get('/', () => {
// Caught and passed down to the errorHandler middleware
throw new Error('something broke!');
});
app.get('/next', function (req, res, next) {
app.get('/next', (req: express.Request, res: express.Response, next) => {
// We can also pass exceptions to next()
process.nextTick(function () {
process.nextTick(() => {
next(new Error('oh no!'));
});
});
@@ -460,7 +460,7 @@ app.use(app.router);
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response) => {
res.status(404);
// respond with html page
@@ -481,7 +481,7 @@ app.use(function (req, res, next) {
// error-handling middleware, take the same form
// as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).
// arity of 4, aka the signature (err, req, res: express.Response, next).
// when connect has an error, it will invoke ONLY error-handling
// middleware.
@@ -491,7 +491,7 @@ app.use(function (req, res, next) {
// would remain being executed, however here
// we simply respond with an error page.
app.use(function (err, req, res, next) {
app.use((err, req, res: express.Response) => {
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
@@ -501,25 +501,25 @@ app.use(function (err, req, res, next) {
// Routes
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.render('index.jade');
});
app.get('/404', function (req, res, next) {
app.get('/404', (req: express.Request, res: express.Response, next) => {
// trigger a 404 since no other middleware
// will match /404 after this one, and we're not
// responding here
next();
});
app.get('/403', function (req, res, next) {
app.get('/403', (req: express.Request, res: express.Response, next) => {
// trigger a 403 error
var err = <any>new Error('not allowed!');
err.status = 403;
next(err);
});
app.get('/500', function (req, res, next) {
app.get('/500', (req: express.Request, res: express.Response, next) => {
// trigger a generic (500) error
next(new Error('keyboard cat!'));
});
@@ -552,7 +552,7 @@ User.prototype.toJSON = function () {
return {
id: this.id,
name: this.name
}
};
};
app.use(express.logger('dev'));
@@ -563,7 +563,7 @@ app.use(express.logger('dev'));
// to the templates, so "expose" will
// be present.
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response, next) => {
res.locals.expose = {};
// you could alias this as req or res.expose
// to make it shorter and less annoying
@@ -572,16 +572,16 @@ app.use(function (req, res, next) {
// pretend we loaded a user
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response, next) => {
req.user = new User('Tobi');
next();
});
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.redirect('/user');
});
app.get('/user', function (req, res) {
app.get('/user', (req: express.Request, res: express.Response) => {
// we only want to expose the user
// to the client for this route:
res.locals.expose.user = req.user;
@@ -593,7 +593,7 @@ console.log('app listening on port 3000');
///////////////////////
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.send('Hello World');
});
@@ -604,33 +604,33 @@ console.log('Express started on port 3000');
// register .md as an engine in express view system
app.engine('md', function (path, options, fn) {
fs.readFile(path, 'utf8', function (err, str) {
app.engine('md', (path, options, fn) => {
fs.readFile(path, 'utf8', (err, str) => {
if (err) return fn(err);
try {
var html = md(str);
html = html.replace(/\{([^}]+)\}/g, function (_, name) {
html = html.replace(/\{([^}]+)\}/g, (_, name) => {
return options[name] || '';
})
});
fn(null, html);
} catch (err) {
fn(err);
}
});
})
});
app.set('views', __dirname + '/views');
// make it the default so we dont need .md
app.set('view engine', 'md');
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.render('index', { title: 'Markdown Example' });
})
});
app.get('/fail', function (req, res) {
app.get('/fail', (req: express.Request, res: express.Response) => {
res.render('missing', { title: 'Markdown Example' });
})
});
if (!module.parent) {
app.listen(3000);
@@ -643,9 +643,9 @@ var mformat: any;
// bodyParser in connect 2.x uses node-formidable to parse
// the multipart form data.
app.use(express.bodyParser())
app.use(express.bodyParser());
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Title: <input type="text" name="title" /></p>'
+ '<p>Image: <input type="file" name="image" /></p>'
@@ -653,7 +653,7 @@ app.get('/', function (req, res) {
+ '</form>');
});
app.post('/', function (req, res, next) {
app.post('/', (req: express.Request, res: express.Response) => {
// the uploaded file can be found as `req.files.image` and the
// title field as `req.body.title`
res.send(mformat('\nuploaded %s (%d Kb) to %s as %s'
@@ -680,7 +680,6 @@ if (!module.parent) {
*/
var online: any;
var redis: any;
var db: any;
// online
@@ -690,7 +689,7 @@ online = online(db);
// activity tracking, in this case using
// the UA string, you would use req.user.id etc
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response, next) => {
// fire-and-forget
online.add(req.headers['user-agent']);
next();
@@ -701,7 +700,7 @@ app.use(function (req, res, next) {
*/
function list(ids) {
return '<ul>' + ids.map(function (id) {
return '<ul>' + ids.map(id => {
return '<li>' + id + '</li>';
}).join('') + '</ul>';
}
@@ -710,8 +709,8 @@ function list(ids) {
* GET users online.
*/
app.get('/', function (req, res, next) {
online.last(5, function (err, ids) {
app.get('/', (req: express.Request, res: express.Response, next) => {
online.last(5, (err, ids) => {
if (err) return next(err);
res.send('<p>Users online: ' + ids.length + '</p>' + list(ids));
});
@@ -724,7 +723,7 @@ console.log('listening on port 3000');
// Convert :to and :from to integers
app.param(['to', 'from'], function (req, res, next, num, name) {
app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => {
req.params[name] = num = parseInt(num, 10);
if (isNaN(num)) {
next(new Error('failed to parseInt ' + num));
@@ -735,7 +734,7 @@ app.param(['to', 'from'], function (req, res, next, num, name) {
// Load user by id
app.param('user', function (req, res, next, id) {
app.param('user', (req: express.Request, res: express.Response, next, id) => {
if (req.user = users[id]) {
next();
} else {
@@ -747,7 +746,7 @@ app.param('user', function (req, res, next, id) {
* GET index.
*/
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.send('Visit /user/0 or /users/0-2');
});
@@ -755,7 +754,7 @@ app.get('/', function (req, res) {
* GET :user.
*/
app.get('/user/:user', function (req, res, next) {
app.get('/user/:user', (req: express.Request, res: express.Response) => {
res.send('user ' + req.user.name);
});
@@ -763,10 +762,10 @@ app.get('/user/:user', function (req, res, next) {
* GET users :from - :to.
*/
app.get('/users/:from-:to', function (req, res, next) {
app.get('/users/:from-:to', (req: express.Request, res: express.Response) => {
var from = req.params.from
, to = req.params.to
, names = users.map(function (user) { return user.name; });
, names = users.map(user => { return user.name; });
res.send('users ' + names.slice(from, to).join(', '));
});
@@ -781,7 +780,7 @@ if (!module.parent) {
app.resource = function (path, obj) {
this.get(path, obj.index);
this.get(path + '/:a..:b.:format?', function (req, res) {
this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => {
var a = parseInt(req.params.a, 10)
, b = parseInt(req.params.b, 10)
, format = req.params.format;
@@ -794,19 +793,19 @@ app.resource = function (path, obj) {
// Fake controller.
var FUser = {
index: function (req, res) {
index: (req: express.Request, res: express.Response) => {
res.send(users);
},
show: function (req, res) {
show: (req: express.Request, res: express.Response) => {
res.send(users[req.params.id] || { error: 'Cannot find user' });
},
destroy: function (req, res) {
destroy: (req: express.Request, res: express.Response) => {
var id = req.params.id;
var destroyed = id in users;
delete users[id];
res.send(destroyed ? 'destroyed' : 'Cannot find user');
},
range: function (req, res, a, b, format) {
range: (req: express.Request, res: express.Response, a, b, format) => {
var range = users.slice(a, b + 1);
switch (format) {
case 'json':
@@ -814,7 +813,7 @@ var FUser = {
break;
case 'html':
default:
var html = '<ul>' + range.map(function (user) {
var html = '<ul>' + range.map(user => {
return '<li>' + user.name + '</li>';
}).join('\n') + '</ul>';
res.send(html);
@@ -831,7 +830,7 @@ var FUser = {
app.resource('/users', FUser);
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.send([
'<h1>Examples:</h1> <ul>'
, '<li>GET /users</li>'
@@ -854,7 +853,7 @@ if (!module.parent) {
var verbose: any;
app.map = function (a, route) {
app.map = (a, route) => {
route = route || '';
for (var key in a) {
switch (typeof a[key]) {
@@ -872,25 +871,25 @@ app.map = function (a, route) {
};
var users2 = {
list: function (req, res) {
list: (req: express.Request, res: express.Response) => {
res.send('user list');
},
get: function (req, res) {
get: (req: express.Request, res: express.Response) => {
res.send('user ' + req.params.uid);
},
del: function (req, res) {
del: (req: express.Request, res: express.Response) => {
res.send('delete users');
}
};
var pets2 = {
list: function (req, res) {
list: (req: express.Request, res: express.Response) => {
res.send('user ' + req.params.uid + '\'s pets');
},
del: function (req, res) {
del: (req: express.Request, res: express.Response) => {
res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
}
};
@@ -922,7 +921,7 @@ app.listen(3000);
// curl http://localhost:3000/user/1/edit (unauthorized since this is not you)
// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin)
function loadUser(req, res, next) {
function loadUser(req: express.Request, res: express.Response, next) {
// You would fetch your user from the db
var user = users[req.params.id];
if (user) {
@@ -933,7 +932,7 @@ function loadUser(req, res, next) {
}
}
function andRestrictToSelf(req, res, next) {
function andRestrictToSelf(req: express.Request, res: express.Response, next) {
// If our authenticated user is the user we are viewing
// then everything is fine :)
if (req.authenticatedUser.id == req.user.id) {
@@ -948,13 +947,13 @@ function andRestrictToSelf(req, res, next) {
}
function andRestrictTo(role) {
return function (req, res, next) {
return (req: express.Request, res: express.Response, next) => {
if (req.authenticatedUser.role == role) {
next();
} else {
next(new Error('Unauthorized'));
}
}
};
}
// Middleware for faux authentication
@@ -962,24 +961,24 @@ function andRestrictTo(role) {
// but this illustrates how an authenticated user
// may interact with middleware
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response, next) => {
req.authenticatedUser = users[0];
next();
});
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.redirect('/user/0');
});
app.get('/user/:id', loadUser, function (req, res) {
app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => {
res.send('Viewing user ' + req.user.name);
});
app.get('/user/:id/edit', loadUser, andRestrictToSelf, function (req, res) {
app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => {
res.send('Editing user ' + req.user.name);
});
app.del('/user/:id', loadUser, andRestrictTo('admin'), function (req, res) {
app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => {
res.send('Deleted user ' + req.user.name);
});
@@ -1003,7 +1002,7 @@ db.sadd('cat', 'luna');
* GET the search page.
*/
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.render('search');
});
@@ -1011,9 +1010,9 @@ app.get('/', function (req, res) {
* GET search for :query.
*/
app.get('/search/:query?', function (req, res) {
app.get('/search/:query?', (req: express.Request, res: express.Response) => {
var query = req.params.query;
db.smembers(query, function (err, vals) {
db.smembers(query, (err, vals) => {
if (err) return res.send(500);
res.send(vals);
});
@@ -1026,7 +1025,7 @@ app.get('/search/:query?', function (req, res) {
* template.
*/
app.get('/client.js', function (req, res) {
app.get('/client.js', (req: express.Request, res: express.Response) => {
res.sendfile(__dirname + '/client.js');
});
@@ -1045,7 +1044,7 @@ app.use(express.cookieParser('keyboard cat'));
// Populates req.session
app.use(express.session());
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
var body = '';
if (req.session.views) {
++req.session.views;
@@ -1118,11 +1117,11 @@ var main = express();
main.use(express.logger('dev'));
main.get('/', function (req, res) {
res.send('Hello from main app!')
main.get('/', (req: express.Request, res: express.Response) => {
res.send('Hello from main app!');
});
main.get('/:sub', function (req, res) {
main.get('/:sub', (req: express.Request, res: express.Response) => {
res.send('requsted ' + req.params.sub);
});
@@ -1130,12 +1129,12 @@ main.get('/:sub', function (req, res) {
var redirect = express();
redirect.all('*', function (req, res) {
redirect.all('*', (req: express.Request, res: express.Response) => {
console.log(req.subdomains);
res.redirect('http://example.com:3000/' + req.subdomains[0]);
});
app.use(express.vhost('*.example.com', redirect))
app.use(express.vhost('*.example.com', redirect));
app.use(express.vhost('example.com', main));
app.listen(3000);
@@ -1162,7 +1161,7 @@ function merror(status, msg) {
// meaning only paths prefixed with "/api"
// will cause this middleware to be invoked
app.use('/api', function (req, res, next) {
app.use('/api', (req, res: express.Response, next) => {
var key = req.query['api-key'];
// key isnt present
@@ -1186,7 +1185,7 @@ app.use(app.router);
// it will be passed through the defined middleware
// in order, but ONLY those with an arity of 4, ignoring
// regular middleware.
app.use(function (err, req, res, next) {
app.use((err, req, res: express.Response) => {
// whatever you want here, feel free to populate
// properties on `err` to treat it differently in here.
res.send(err.status || 500, { error: err.message });
@@ -1195,7 +1194,7 @@ app.use(function (err, req, res, next) {
// our custom JSON 404 middleware. Since it's placed last
// it will be the last middleware called, if all others
// invoke next() and do not respond.
app.use(function (req, res) {
app.use((req: express.Request, res: express.Response) => {
res.send(404, { error: "Lame, can't find that" });
});
@@ -1223,15 +1222,15 @@ var userRepos = {
// we now can assume the api key is valid,
// and simply expose the data
app.get('/api/users', function (req, res, next) {
app.get('/api/users', (req: express.Request, res: express.Response) => {
res.send(users);
});
app.get('/api/repos', function (req, res, next) {
app.get('/api/repos', (req: express.Request, res: express.Response) => {
res.send(repos);
});
app.get('/api/user/:name/repos', function (req, res, next) {
app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => {
var name = req.params.name
, user = userRepos[name];
@@ -1248,19 +1247,19 @@ if (!module.parent) {
function test_general() {
app.use(function (err, req, res, next) {
app.use((err, req, res: express.Response) => {
console.error(err.stack);
res.send(500, 'Something broke!');
});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(function (err, req, res, next) { });
app.use(() => {});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.get('/', function (req, res) {
app.get('/', (req: express.Request, res: express.Response) => {
res.send('hello world');
});
@@ -1285,18 +1284,18 @@ function test_general() {
app.set('db uri', 'localhost/dev');
});
app.configure('stage', 'production', function () { });
app.configure('stage', 'production', () => {});
app.configure('1', '2', '3', function () { });
app.configure('1', '2', '3', () => {});
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response) => {
res.send('Hello World');
});
app.engine('jade', require('jade').__express);
var User;
app.param('user', (req, res, next, id) => {
app.param('user', (req: express.Request, res: express.Response, next, id) => {
User.find(id, (err, user) =>{
if (err) {
next(err);
@@ -1309,7 +1308,7 @@ function test_general() {
});
});
app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req, res) => {
app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => {
var from = req.params[0];
var to = req.params[1] || 'HEAD';
res.send('commit range ' + from + '..' + to);
@@ -1319,7 +1318,7 @@ function test_general() {
app.locals.strftime = require('strftime');
var requireAuthentication;
var loadUser = function () { };
var loadUser = () => {};
app.all('*', requireAuthentication, loadUser);
app.all('*', loadUser);
app.all('*', loadUser, loadUser, loadUser);
@@ -1331,9 +1330,9 @@ function test_general() {
phone: '1-250-858-9990',
email: 'me@myapp.com'
});
app.render('email', function (err, html) { });
app.render('email', () => {});
app.render('email', { name: 'Tobi' }, function (err, html) { });
app.render('email', { name: 'Tobi' }, () => {});
}
function test_request() {
@@ -1413,24 +1412,24 @@ function test_response() {
res.type('application/json');
res.format({
'text/plain': function () {
'text/plain': () => {
res.send('hey');
},
'text/html': function () {
'text/html': () => {
res.send('hey');
},
'application/json': function () {
'application/json': () => {
res.send({ message: 'hey' });
}
});
res.attachment();
res.attachment('path/to/logo.png');
app.get('/user/:uid/photos/:file', function (req, res) {
app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => {
var uid = req.params.uid
, file = req.params.file;
req.user.mayViewFilesFrom(uid, function (yes) {
req.user.mayViewFilesFrom(uid, yes => {
if (yes) {
res.sendfile('/uploads/' + uid + '/' + file);
} else {
@@ -1441,7 +1440,7 @@ function test_response() {
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('/report-12345.pdf', 'report.pdf', function (err) {
res.download('/report-12345.pdf', 'report.pdf', err => {
if (err) { } else { }
});
@@ -1450,19 +1449,19 @@ function test_response() {
last: 'http://api.example.com/users?page=5'
});
app.use(function (req, res, next) {
app.use((req: express.Request, res: express.Response, next) => {
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});
res.render('index', function (err, html) { });
res.render('user', { name: 'Tobi' }, function (err, html) { });
res.render('index', () => {});
res.render('user', { name: 'Tobi' }, () => {});
}
function test_middleware() {
app.use(express.basicAuth('username', 'password'));
app.use(express.basicAuth(function (user, pass) {
app.use(express.basicAuth((user, pass) => {
return 'tj' == user && 'wahoo' == pass;
}));
app.use(express.bodyParser());
+25 -28
View File
@@ -125,6 +125,8 @@ declare module "express" {
success: string;
views: any;
count: number;
}
interface Request {
@@ -156,6 +158,8 @@ declare module "express" {
header(name: string): string;
headers: string[];
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
@@ -235,19 +239,8 @@ declare module "express" {
/**
* Return an array of Accepted media types
* ordered from highest quality to lowest.
*
* Examples:
*
* [ { value: 'application/json',
* quality: 1,
* type: 'application',
* subtype: 'json' },
* { value: 'text/html',
* quality: 0.5,
* type: 'text',
* subtype: 'html' } ]
*/
accepted: any[];
accepted: MediaType[];
/**
* Return an array of Accepted languages
@@ -417,6 +410,8 @@ declare module "express" {
user: any;
authenticatedUser: any;
files: any;
/**
@@ -434,6 +429,20 @@ declare module "express" {
signedCookies: any;
originalUrl: string;
url: string;
}
interface MediaType {
value: string;
quality: number;
type: string;
subtype: string;
}
interface Send {
(status: number, body?: any): Response;
(body: any): Response;
}
interface Response extends http.ServerResponse {
@@ -469,11 +478,7 @@ declare module "express" {
* res.send(404, 'Sorry, cant find that');
* res.send(404);
*/
send(status: number): Response;
send(bodyOrStatus: any): Response;
send(status: number, body: any): Response;
send: Send;
/**
* Send JSON response.
@@ -485,11 +490,7 @@ declare module "express" {
* res.json(500, 'oh noes!');
* res.json(404, 'I dont have that');
*/
json(status: number): Response;
json(bodyOrStatus: any): Response;
json(status: number, body: any): Response;
json: Send;
/**
* Send JSON response with JSONP callback support.
@@ -501,11 +502,7 @@ declare module "express" {
* res.jsonp(500, 'oh noes!');
* res.jsonp(404, 'I dont have that');
*/
jsonp(status: number): Response;
jsonp(bodyOrStatus: any): Response;
jsonp(status: number, body: any): Response;
jsonp: Send;
/**
* Transfer the file at the given `path`.
@@ -884,7 +881,7 @@ declare module "express" {
*/
param(name: string, fn: Function): Application;
param(name: any[], fn: Function): Application;
param(name: string[], fn: Function): Application;
/**
* Assign `setting` to `val`, or return `setting`'s value.