diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 62562b74a3b..00000000000 --- a/.eslintignore +++ /dev/null @@ -1,2 +0,0 @@ -coverage -node_modules diff --git a/.eslintrc.yml b/.eslintrc.yml deleted file mode 100644 index f9359bf2892..00000000000 --- a/.eslintrc.yml +++ /dev/null @@ -1,14 +0,0 @@ -root: true -env: - es2022: true - node: true -rules: - eol-last: error - eqeqeq: [error, allow-null] - indent: [error, 2, { MemberExpression: "off", SwitchCase: 1 }] - no-trailing-spaces: error - no-unused-vars: [error, { vars: all, args: none, ignoreRestSiblings: true }] - no-restricted-globals: - - error - - name: Buffer - message: Use `import { Buffer } from "node:buffer"` instead of the global Buffer. diff --git a/benchmarks/middleware.js b/benchmarks/middleware.js index fed97ba8ce4..e05ec643e81 100644 --- a/benchmarks/middleware.js +++ b/benchmarks/middleware.js @@ -1,20 +1,19 @@ - -var express = require('..'); -var app = express(); +const express = require('../') +const app = express() // number of middleware -var n = parseInt(process.env.MW || '1', 10); -console.log(' %s middleware', n); +let n = parseInt(process.env.MW || '1', 10) +console.log(' %s middleware', n) while (n--) { - app.use(function(req, res, next){ - next(); - }); + app.use((req, res, next) => { + next() + }) } -app.use(function(req, res){ +app.use((req, res) => { res.send('Hello World') -}); +}) -app.listen(3333); +app.listen(3333) diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 00000000000..66661be5427 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,23 @@ +import globals from 'globals' +import neostandard from 'neostandard' + +// globals present in Node.js but not in browsers. +const nodeGlobals = Object.keys(globals.node).filter(g => !Object.keys(globals.browser).includes(g)) + +// Node.js-specific globals that are allowed. +const allowedGlobals = [ + 'require', 'module', 'exports', '__dirname', 'process', 'setImmediate' +] + +export default [ + ...neostandard({ + env: ['mocha'] + }), + { + rules: { + 'global-require': 'warn', + 'no-restricted-globals': ['error', ...nodeGlobals.filter(g => !allowedGlobals.includes(g))], + 'n/handle-callback-err': 'off' + } + } +] diff --git a/examples/auth/index.js b/examples/auth/index.js index 40b73e6de16..a6e2d641f4f 100644 --- a/examples/auth/index.js +++ b/examples/auth/index.js @@ -4,17 +4,17 @@ * Module dependencies. */ -var express = require('../..'); -var hash = require('pbkdf2-password')() -var path = require('node:path'); -var session = require('express-session'); +const express = require('../../') +const hash = require('pbkdf2-password')() +const path = require('node:path') +const session = require('express-session') -var app = module.exports = express(); +const app = module.exports = express() // config -app.set('view engine', 'ejs'); -app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs') +app.set('views', path.join(__dirname, 'views')) // middleware @@ -23,112 +23,111 @@ app.use(session({ resave: false, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'shhhh, very secret' -})); +})) // Session-persisted message middleware -app.use(function(req, res, next){ - var err = req.session.error; - var msg = req.session.success; - delete req.session.error; - delete req.session.success; - res.locals.message = ''; - if (err) res.locals.message = '

' + err + '

'; - if (msg) res.locals.message = '

' + msg + '

'; - next(); -}); +app.use((req, res, next) => { + const err = req.session.error + const msg = req.session.success + delete req.session.error + delete req.session.success + res.locals.message = '' + if (err) res.locals.message = '

' + err + '

' + if (msg) res.locals.message = '

' + msg + '

' + next() +}) // dummy database -var users = { +const users = { tj: { name: 'tj' } -}; +} // when you create a user, generate a salt // and hash the password ('foobar' is the pass here) -hash({ password: 'foobar' }, function (err, pass, salt, hash) { - if (err) throw err; +hash({ password: 'foobar' }, (err, pass, salt, hash) => { + if (err) throw err // store the salt & hash in the "db" - users.tj.salt = salt; - users.tj.hash = hash; -}); - + users.tj.salt = salt + users.tj.hash = hash +}) // Authenticate using our plain-object database of doom! -function authenticate(name, pass, fn) { - if (!module.parent) console.log('authenticating %s:%s', name, pass); - var user = users[name]; +function authenticate (name, pass, fn) { + if (!module.parent) console.log('authenticating %s:%s', name, pass) + const user = users[name] // query the db for the given username if (!user) return fn(null, null) // 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({ password: pass, salt: user.salt }, function (err, pass, salt, hash) { - if (err) return fn(err); + hash({ password: pass, salt: user.salt }, (err, pass, salt, hash) => { + if (err) return fn(err) if (hash === user.hash) return fn(null, user) fn(null, null) - }); + }) } -function restrict(req, res, next) { +function restrict (req, res, next) { if (req.session.user) { - next(); + next() } else { - req.session.error = 'Access denied!'; - res.redirect('/login'); + req.session.error = 'Access denied!' + res.redirect('/login') } } -app.get('/', function(req, res){ - res.redirect('/login'); -}); +app.get('/', (req, res) => { + res.redirect('/login') +}) -app.get('/restricted', restrict, function(req, res){ - res.send('Wahoo! restricted area, click to logout'); -}); +app.get('/restricted', restrict, (req, res) => { + res.send('Wahoo! restricted area, click to logout') +}) -app.get('/logout', function(req, res){ +app.get('/logout', (req, res) => { // destroy the user's session to log them out // will be re-created next request - req.session.destroy(function(){ - res.redirect('/'); - }); -}); + req.session.destroy(() => { + res.redirect('/') + }) +}) -app.get('/login', function(req, res){ - res.render('login'); -}); +app.get('/login', (req, res) => { + res.render('login') +}) -app.post('/login', function (req, res, next) { +app.post('/login', (req, res, next) => { if (!req.body) return res.sendStatus(400) - authenticate(req.body.username, req.body.password, function(err, user){ + authenticate(req.body.username, req.body.password, (err, user) => { if (err) return next(err) 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 - req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; - res.redirect(req.get('Referrer') || '/'); - }); + req.session.user = user + req.session.success = 'Authenticated as ' + user.name + + ' click to logout. ' + + ' You may now access /restricted.' + res.redirect(req.get('Referrer') || '/') + }) } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; - res.redirect('/login'); + req.session.error = 'Authentication failed, please check your ' + + ' username and password.' + + ' (use "tj" and "foobar")' + res.redirect('/login') } - }); -}); + }) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/content-negotiation/db.js b/examples/content-negotiation/db.js index f59b23bf18e..501e84966a1 100644 --- a/examples/content-negotiation/db.js +++ b/examples/content-negotiation/db.js @@ -1,9 +1,9 @@ 'use strict' -var users = []; +const users = [] -users.push({ name: 'Tobi' }); -users.push({ name: 'Loki' }); -users.push({ name: 'Jane' }); +users.push({ name: 'Tobi' }) +users.push({ name: 'Loki' }) +users.push({ name: 'Jane' }) -module.exports = users; +module.exports = users diff --git a/examples/content-negotiation/index.js b/examples/content-negotiation/index.js index 280a4e22998..c417499d07a 100644 --- a/examples/content-negotiation/index.js +++ b/examples/content-negotiation/index.js @@ -1,46 +1,43 @@ 'use strict' -var express = require('../../'); -var app = module.exports = express(); -var users = require('./db'); +const express = require('../../') +const app = module.exports = express() +const users = require('./db') // so either you can deal with different types of formatting // for expected response in index.js -app.get('/', function(req, res){ +app.get('/', (req, res) => { res.format({ - html: function(){ - res.send(''); + html: function () { + res.send('') }, - text: function(){ - res.send(users.map(function(user){ - return ' - ' + user.name + '\n'; - }).join('')); + text: function () { + res.send(users.map((user) => ' - ' + user.name + '\n').join('')) }, - json: function(){ - res.json(users); + json: function () { + res.json(users) } - }); -}); + }) +}) // or you could write a tiny middleware like // this to add a layer of abstraction // and make things a bit more declarative: -function format(path) { - var obj = require(path); - return function(req, res){ - res.format(obj); - }; +function format (path) { + // eslint-disable-next-line global-require + const obj = require(path) + return function (req, res) { + res.format(obj) + } } -app.get('/users', format('./users')); +app.get('/users', format('./users')) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/content-negotiation/users.js b/examples/content-negotiation/users.js index fe703e73a9a..e6badf7aafc 100644 --- a/examples/content-negotiation/users.js +++ b/examples/content-negotiation/users.js @@ -1,19 +1,15 @@ 'use strict' -var users = require('./db'); +const users = require('./db') -exports.html = function(req, res){ - res.send(''); -}; +exports.html = function (req, res) { + res.send('') +} -exports.text = function(req, res){ - res.send(users.map(function(user){ - return ' - ' + user.name + '\n'; - }).join('')); -}; +exports.text = function (req, res) { + res.send(users.map((user) => ' - ' + user.name + '\n').join('')) +} -exports.json = function(req, res){ - res.json(users); -}; +exports.json = function (req, res) { + res.json(users) +} diff --git a/examples/cookie-sessions/index.js b/examples/cookie-sessions/index.js index 83b6faee82b..51d310543ab 100644 --- a/examples/cookie-sessions/index.js +++ b/examples/cookie-sessions/index.js @@ -4,22 +4,22 @@ * Module dependencies. */ -var cookieSession = require('cookie-session'); -var express = require('../../'); +const cookieSession = require('cookie-session') +const express = require('../../') -var app = module.exports = express(); +const app = module.exports = express() // add req.session cookie support -app.use(cookieSession({ secret: 'manny is cool' })); +app.use(cookieSession({ secret: 'manny is cool' })) // do something with the session -app.get('/', function (req, res) { +app.get('/', (req, res) => { req.session.count = (req.session.count || 0) + 1 res.send('viewed ' + req.session.count + ' times\n') }) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/cookies/index.js b/examples/cookies/index.js index 0620cb40e45..135f4e4f0dd 100644 --- a/examples/cookies/index.js +++ b/examples/cookies/index.js @@ -4,10 +4,10 @@ * Module dependencies. */ -var express = require('../../'); -var app = module.exports = express(); -var logger = require('morgan'); -var cookieParser = require('cookie-parser'); +const express = require('../../') +const app = module.exports = express() +const logger = require('morgan') +const cookieParser = require('cookie-parser') // custom log format if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url')) @@ -16,38 +16,38 @@ if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url')) // req.cookies and req.signedCookies // when the secret is passed, used // for signing the cookies. -app.use(cookieParser('my secret here')); +app.use(cookieParser('my secret here')) // parses x-www-form-urlencoded app.use(express.urlencoded()) -app.get('/', function(req, res){ +app.get('/', (req, res) => { if (req.cookies.remember) { - res.send('Remembered :). Click to forget!.'); + res.send('Remembered :). Click to forget!.') } else { - res.send('

Check to ' - + '.

'); + res.send('

Check to ' + + '.

') } -}); +}) -app.get('/forget', function(req, res){ - res.clearCookie('remember'); - res.redirect(req.get('Referrer') || '/'); -}); +app.get('/forget', (req, res) => { + res.clearCookie('remember') + res.redirect(req.get('Referrer') || '/') +}) -app.post('/', function(req, res){ - var minute = 60000; +app.post('/', (req, res) => { + const minute = 60000 if (req.body && req.body.remember) { res.cookie('remember', 1, { maxAge: minute }) } - res.redirect(req.get('Referrer') || '/'); -}); + res.redirect(req.get('Referrer') || '/') +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/downloads/index.js b/examples/downloads/index.js index ddc549ffec7..ac39b5da939 100644 --- a/examples/downloads/index.js +++ b/examples/downloads/index.js @@ -4,37 +4,37 @@ * Module dependencies. */ -var express = require('../../'); -var path = require('node:path'); +const express = require('../../') +const path = require('node:path') -var app = module.exports = express(); +const app = module.exports = express() // path to where the files are stored on disk -var FILES_DIR = path.join(__dirname, 'files') +const FILES_DIR = path.join(__dirname, 'files') -app.get('/', function(req, res){ +app.get('/', (req, res) => { res.send('') -}); +}) // /files/* is accessed via req.params[0] // but here we name it :file -app.get('/files/*file', function (req, res, next) { - res.download(req.params.file.join('/'), { root: FILES_DIR }, function (err) { - if (!err) return; // file sent - if (err.status !== 404) return next(err); // non-404 error +app.get('/files/*file', (req, res, next) => { + res.download(req.params.file.join('/'), { root: FILES_DIR }, (err) => { + if (!err) return // file sent + if (err.status !== 404) return next(err) // non-404 error // file for download not found - res.statusCode = 404; - res.send('Cant find that file, sorry!'); - }); -}); + res.statusCode = 404 + res.send('Cant find that file, sorry!') + }) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/ejs/index.js b/examples/ejs/index.js index 0940d0624fb..c65db86eb82 100644 --- a/examples/ejs/index.js +++ b/examples/ejs/index.js @@ -4,10 +4,10 @@ * Module dependencies. */ -var express = require('../../'); -var path = require('node:path'); +const express = require('../../') +const path = require('node:path') -var app = module.exports = express(); +const app = module.exports = express() // Register ejs as .html. If we did // not call this, we would need to @@ -20,38 +20,38 @@ var app = module.exports = express(); // we simply pass _any_ function, in this // case `ejs.__express`. -app.engine('.html', require('ejs').__express); +app.engine('.html', require('ejs').__express) // Optional since express defaults to CWD/views -app.set('views', path.join(__dirname, 'views')); +app.set('views', path.join(__dirname, 'views')) // Path to our public directory -app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'public'))) // Without this you would need to // supply the extension to res.render() // ex: res.render('users.html'). -app.set('view engine', 'html'); +app.set('view engine', 'html') // Dummy users -var users = [ +const users = [ { name: 'tobi', email: 'tobi@learnboost.com' }, { name: 'loki', email: 'loki@learnboost.com' }, { name: 'jane', email: 'jane@learnboost.com' } -]; +] -app.get('/', function(req, res){ +app.get('/', (req, res) => { res.render('users', { - users: users, - title: "EJS example", - header: "Some users" - }); -}); + users, + title: 'EJS example', + header: 'Some users' + }) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/error-pages/index.js b/examples/error-pages/index.js index 0863120bc8f..6a2bbdb08dc 100644 --- a/examples/error-pages/index.js +++ b/examples/error-pages/index.js @@ -4,51 +4,51 @@ * Module dependencies. */ -var express = require('../../'); -var path = require('node:path'); -var app = module.exports = express(); -var logger = require('morgan'); -var silent = process.env.NODE_ENV === 'test' +const express = require('../../') +const path = require('node:path') +const app = module.exports = express() +const logger = require('morgan') +const silent = process.env.NODE_ENV === 'test' // general config -app.set('views', path.join(__dirname, 'views')); -app.set('view engine', 'ejs'); +app.set('views', path.join(__dirname, 'views')) +app.set('view engine', 'ejs') // our custom "verbose errors" setting // which we can use in the templates // via settings['verbose errors'] -app.enable('verbose errors'); +app.enable('verbose errors') // disable them in production // use $ NODE_ENV=production node examples/error-pages if (app.settings.env === 'production') app.disable('verbose errors') -silent || app.use(logger('dev')); +silent || app.use(logger('dev')) // Routes -app.get('/', function(req, res){ - res.render('index.ejs'); -}); +app.get('/', (req, res) => { + res.render('index.ejs') +}) -app.get('/404', function(req, res, next){ +app.get('/404', (req, res, next) => { // trigger a 404 since no other middleware // will match /404 after this one, and we're not // responding here - next(); -}); + next() +}) -app.get('/403', function(req, res, next){ +app.get('/403', (req, res, next) => { // trigger a 403 error - var err = new Error('not allowed!'); - err.status = 403; - next(err); -}); + const err = new Error('not allowed!') + err.status = 403 + next(err) +}) -app.get('/500', function(req, res, next){ +app.get('/500', (req, res, next) => { // trigger a generic (500) error - next(new Error('keyboard cat!')); -}); + next(new Error('keyboard cat!')) +}) // Error handlers @@ -60,8 +60,8 @@ app.get('/500', function(req, res, next){ // $ curl http://localhost:3000/notfound -H "Accept: application/json" // $ curl http://localhost:3000/notfound -H "Accept: text/plain" -app.use(function(req, res, next){ - res.status(404); +app.use((req, res, next) => { + res.status(404) res.format({ html: function () { @@ -74,7 +74,7 @@ app.use(function(req, res, next){ res.type('txt').send('Not found') } }) -}); +}) // error-handling middleware, take the same form // as regular middleware, however they require an @@ -88,16 +88,16 @@ 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, next) => { // we may use properties of the error object // here and next(err) appropriately, or if // we possibly recovered from the error, simply next(). - res.status(err.status || 500); - res.render('500', { error: err }); -}); + res.status(err.status || 500) + res.render('500', { error: err }) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/error/index.js b/examples/error/index.js index d733a81172d..c0eb982511f 100644 --- a/examples/error/index.js +++ b/examples/error/index.js @@ -4,12 +4,12 @@ * Module dependencies. */ -var express = require('../../'); -var logger = require('morgan'); -var app = module.exports = express(); -var test = app.get('env') === 'test' +const express = require('../../') +const logger = require('morgan') +const app = module.exports = express() +const test = app.get('env') === 'test' -if (!test) app.use(logger('dev')); +if (!test) app.use(logger('dev')) // error handling middleware have an arity of 4 // instead of the typical (req, res, next), @@ -17,37 +17,37 @@ if (!test) app.use(logger('dev')); // middleware, you may have several of them, // in different orders etc. -function error(err, req, res, next) { +function error (err, req, res, next) { // log it - if (!test) console.error(err.stack); + if (!test) console.error(err.stack) // respond with 500 "Internal Server Error". - res.status(500); - res.send('Internal Server Error'); + res.status(500) + res.send('Internal Server Error') } -app.get('/', function () { +app.get('/', () => { // Caught and passed down to the errorHandler middleware - throw new Error('something broke!'); -}); + throw new Error('something broke!') +}) -app.get('/next', function(req, res, next){ +app.get('/next', (req, res, next) => { // We can also pass exceptions to next() // The reason for process.nextTick() is to show that // next() can be called inside an async operation, // in real life it can be a DB read or HTTP request. - process.nextTick(function(){ - next(new Error('oh no!')); - }); -}); + process.nextTick(() => { + next(new Error('oh no!')) + }) +}) // the error handler is placed after routes // if it were above it would not receive errors // from app.get() etc -app.use(error); +app.use(error) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/hello-world/index.js b/examples/hello-world/index.js index 8c1855c2eb7..5236bc13e5a 100644 --- a/examples/hello-world/index.js +++ b/examples/hello-world/index.js @@ -1,15 +1,15 @@ 'use strict' -var express = require('../../'); +const express = require('../../') -var app = module.exports = express() +const app = module.exports = express() -app.get('/', function(req, res){ - res.send('Hello World'); -}); +app.get('/', (req, res) => { + res.send('Hello World') +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/markdown/index.js b/examples/markdown/index.js index 53e40ac38e4..5330c3236bc 100644 --- a/examples/markdown/index.js +++ b/examples/markdown/index.js @@ -4,41 +4,39 @@ * Module dependencies. */ -var escapeHtml = require('escape-html'); -var express = require('../..'); -var fs = require('node:fs'); -var marked = require('marked'); -var path = require('node:path'); +const escapeHtml = require('escape-html') +const express = require('../../') +const fs = require('node:fs') +const marked = require('marked') +const path = require('node:path') -var app = module.exports = express(); +const app = module.exports = express() // register .md as an engine in express view system -app.engine('md', function(path, options, fn){ - fs.readFile(path, 'utf8', function(err, str){ - if (err) return fn(err); - var html = marked.parse(str).replace(/\{([^}]+)\}/g, function(_, name){ - return escapeHtml(options[name] || ''); - }); - fn(null, html); - }); -}); +app.engine('md', (path, options, fn) => { + fs.readFile(path, 'utf8', (err, str) => { + if (err) return fn(err) + const html = marked.parse(str).replace(/\{([^}]+)\}/g, (_, name) => escapeHtml(options[name] || '')) + fn(null, html) + }) +}) -app.set('views', path.join(__dirname, 'views')); +app.set('views', path.join(__dirname, 'views')) // make it the default, so we don't need .md -app.set('view engine', 'md'); +app.set('view engine', 'md') -app.get('/', function(req, res){ - res.render('index', { title: 'Markdown Example' }); -}); +app.get('/', (req, res) => { + res.render('index', { title: 'Markdown Example' }) +}) -app.get('/fail', function(req, res){ - res.render('missing', { title: 'Markdown Example' }); -}); +app.get('/fail', (req, res) => { + res.render('missing', { title: 'Markdown Example' }) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/multi-router/controllers/api_v1.js b/examples/multi-router/controllers/api_v1.js index a301e3ee72d..f9dd06314bc 100644 --- a/examples/multi-router/controllers/api_v1.js +++ b/examples/multi-router/controllers/api_v1.js @@ -1,15 +1,15 @@ 'use strict' -var express = require('../../..'); +const express = require('../../../') -var apiv1 = express.Router(); +const apiv1 = express.Router() -apiv1.get('/', function(req, res) { - res.send('Hello from APIv1 root route.'); -}); +apiv1.get('/', (req, res) => { + res.send('Hello from APIv1 root route.') +}) -apiv1.get('/users', function(req, res) { - res.send('List of APIv1 users.'); -}); +apiv1.get('/users', (req, res) => { + res.send('List of APIv1 users.') +}) -module.exports = apiv1; +module.exports = apiv1 diff --git a/examples/multi-router/controllers/api_v2.js b/examples/multi-router/controllers/api_v2.js index e997fb1f88c..bdb7699b8aa 100644 --- a/examples/multi-router/controllers/api_v2.js +++ b/examples/multi-router/controllers/api_v2.js @@ -1,15 +1,15 @@ 'use strict' -var express = require('../../..'); +const express = require('../../../') -var apiv2 = express.Router(); +const apiv2 = express.Router() -apiv2.get('/', function(req, res) { - res.send('Hello from APIv2 root route.'); -}); +apiv2.get('/', (req, res) => { + res.send('Hello from APIv2 root route.') +}) -apiv2.get('/users', function(req, res) { - res.send('List of APIv2 users.'); -}); +apiv2.get('/users', (req, res) => { + res.send('List of APIv2 users.') +}) -module.exports = apiv2; +module.exports = apiv2 diff --git a/examples/multi-router/index.js b/examples/multi-router/index.js index dbfd2841262..44f264b3aa2 100644 --- a/examples/multi-router/index.js +++ b/examples/multi-router/index.js @@ -1,18 +1,18 @@ 'use strict' -var express = require('../..'); +const express = require('../../') -var app = module.exports = express(); +const app = module.exports = express() -app.use('/api/v1', require('./controllers/api_v1')); -app.use('/api/v2', require('./controllers/api_v2')); +app.use('/api/v1', require('./controllers/api_v1')) +app.use('/api/v2', require('./controllers/api_v2')) -app.get('/', function(req, res) { +app.get('/', (req, res) => { res.send('Hello from root route.') -}); +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/mvc/controllers/main/index.js b/examples/mvc/controllers/main/index.js index 74cde191cd8..ad2956d00c2 100644 --- a/examples/mvc/controllers/main/index.js +++ b/examples/mvc/controllers/main/index.js @@ -1,5 +1,5 @@ 'use strict' -exports.index = function(req, res){ - res.redirect('/users'); -}; +exports.index = function (req, res) { + res.redirect('/users') +} diff --git a/examples/mvc/controllers/pet/index.js b/examples/mvc/controllers/pet/index.js index 214160f9a46..48e9d92bf37 100644 --- a/examples/mvc/controllers/pet/index.js +++ b/examples/mvc/controllers/pet/index.js @@ -4,28 +4,28 @@ * Module dependencies. */ -var db = require('../../db'); +const db = require('../../db') -exports.engine = 'ejs'; +exports.engine = 'ejs' -exports.before = function(req, res, next){ - var pet = db.pets[req.params.pet_id]; - if (!pet) return next('route'); - req.pet = pet; - next(); -}; +exports.before = function (req, res, next) { + const pet = db.pets[req.params.pet_id] + if (!pet) return next('route') + req.pet = pet + next() +} -exports.show = function(req, res, next){ - res.render('show', { pet: req.pet }); -}; +exports.show = function (req, res, next) { + res.render('show', { pet: req.pet }) +} -exports.edit = function(req, res, next){ - res.render('edit', { pet: req.pet }); -}; +exports.edit = function (req, res, next) { + res.render('edit', { pet: req.pet }) +} -exports.update = function(req, res, next){ - var body = req.body; - req.pet.name = body.pet.name; - res.message('Information updated!'); - res.redirect('/pet/' + req.pet.id); -}; +exports.update = function (req, res, next) { + const body = req.body + req.pet.name = body.pet.name + res.message('Information updated!') + res.redirect('/pet/' + req.pet.id) +} diff --git a/examples/mvc/controllers/user-pet/index.js b/examples/mvc/controllers/user-pet/index.js index 42a29adebe7..cd90f4f23c1 100644 --- a/examples/mvc/controllers/user-pet/index.js +++ b/examples/mvc/controllers/user-pet/index.js @@ -4,19 +4,19 @@ * Module dependencies. */ -var db = require('../../db'); +const db = require('../../db') -exports.name = 'pet'; -exports.prefix = '/user/:user_id'; +exports.name = 'pet' +exports.prefix = '/user/:user_id' -exports.create = function(req, res, next){ - var id = req.params.user_id; - var user = db.users[id]; - var body = req.body; - if (!user) return next('route'); - var pet = { name: body.pet.name }; - pet.id = db.pets.push(pet) - 1; - user.pets.push(pet); - res.message('Added pet ' + body.pet.name); - res.redirect('/user/' + id); -}; +exports.create = function (req, res, next) { + const id = req.params.user_id + const user = db.users[id] + const body = req.body + if (!user) return next('route') + const pet = { name: body.pet.name } + pet.id = db.pets.push(pet) - 1 + user.pets.push(pet) + res.message('Added pet ' + body.pet.name) + res.redirect('/user/' + id) +} diff --git a/examples/mvc/controllers/user/index.js b/examples/mvc/controllers/user/index.js index ec3ae4c8110..f9c6dc318bc 100644 --- a/examples/mvc/controllers/user/index.js +++ b/examples/mvc/controllers/user/index.js @@ -4,38 +4,38 @@ * Module dependencies. */ -var db = require('../../db'); +const db = require('../../db') -exports.engine = 'hbs'; +exports.engine = 'hbs' -exports.before = function(req, res, next){ - var id = req.params.user_id; - if (!id) return next(); +exports.before = function (req, res, next) { + const id = req.params.user_id + if (!id) return next() // pretend to query a database... - process.nextTick(function(){ - req.user = db.users[id]; + process.nextTick(() => { + req.user = db.users[id] // cant find that user - if (!req.user) return next('route'); + if (!req.user) return next('route') // found it, move on to the routes - next(); - }); -}; - -exports.list = function(req, res, next){ - res.render('list', { users: db.users }); -}; - -exports.edit = function(req, res, next){ - res.render('edit', { user: req.user }); -}; - -exports.show = function(req, res, next){ - res.render('show', { user: req.user }); -}; - -exports.update = function(req, res, next){ - var body = req.body; - req.user.name = body.user.name; - res.message('Information updated!'); - res.redirect('/user/' + req.user.id); -}; + next() + }) +} + +exports.list = function (req, res, next) { + res.render('list', { users: db.users }) +} + +exports.edit = function (req, res, next) { + res.render('edit', { user: req.user }) +} + +exports.show = function (req, res, next) { + res.render('show', { user: req.user }) +} + +exports.update = function (req, res, next) { + const body = req.body + req.user.name = body.user.name + res.message('Information updated!') + res.redirect('/user/' + req.user.id) +} diff --git a/examples/mvc/db.js b/examples/mvc/db.js index 94d1480f9b7..12101d50e9d 100644 --- a/examples/mvc/db.js +++ b/examples/mvc/db.js @@ -2,15 +2,15 @@ // faux database -var pets = exports.pets = []; +const pets = exports.pets = [] -pets.push({ name: 'Tobi', id: 0 }); -pets.push({ name: 'Loki', id: 1 }); -pets.push({ name: 'Jane', id: 2 }); -pets.push({ name: 'Raul', id: 3 }); +pets.push({ name: 'Tobi', id: 0 }) +pets.push({ name: 'Loki', id: 1 }) +pets.push({ name: 'Jane', id: 2 }) +pets.push({ name: 'Raul', id: 3 }) -var users = exports.users = []; +const users = exports.users = [] -users.push({ name: 'TJ', pets: [pets[0], pets[1], pets[2]], id: 0 }); -users.push({ name: 'Guillermo', pets: [pets[3]], id: 1 }); -users.push({ name: 'Nathan', pets: [], id: 2 }); +users.push({ name: 'TJ', pets: [pets[0], pets[1], pets[2]], id: 0 }) +users.push({ name: 'Guillermo', pets: [pets[3]], id: 1 }) +users.push({ name: 'Nathan', pets: [], id: 2 }) diff --git a/examples/mvc/index.js b/examples/mvc/index.js index 1d8aa0e3c31..014fbc8e0dd 100644 --- a/examples/mvc/index.js +++ b/examples/mvc/index.js @@ -4,60 +4,60 @@ * Module dependencies. */ -var express = require('../..'); -var logger = require('morgan'); -var path = require('node:path'); -var session = require('express-session'); -var methodOverride = require('method-override'); +const express = require('../../') +const logger = require('morgan') +const path = require('node:path') +const session = require('express-session') +const methodOverride = require('method-override') -var app = module.exports = express(); +const app = module.exports = express() // set our default template engine to "ejs" // which prevents the need for using file extensions -app.set('view engine', 'ejs'); +app.set('view engine', 'ejs') // set views for error and 404 pages -app.set('views', path.join(__dirname, 'views')); +app.set('views', path.join(__dirname, 'views')) // define a custom res.message() method // which stores messages in the session -app.response.message = function(msg){ +app.response.message = function (msg) { // reference `req.session` via the `this.req` reference - var sess = this.req.session; + const sess = this.req.session // simply add the msg to an array for later - sess.messages = sess.messages || []; - sess.messages.push(msg); - return this; -}; + sess.messages = sess.messages || [] + sess.messages.push(msg) + return this +} // log -if (!module.parent) app.use(logger('dev')); +if (!module.parent) app.use(logger('dev')) // serve static files -app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'public'))) // session support app.use(session({ resave: false, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'some secret here' -})); +})) // parse request bodies (req.body) app.use(express.urlencoded({ extended: true })) // allow overriding methods in query (?_method=put) -app.use(methodOverride('_method')); +app.use(methodOverride('_method')) // expose the "messages" local variable when views are rendered -app.use(function(req, res, next){ - var msgs = req.session.messages || []; +app.use((req, res, next) => { + const msgs = req.session.messages || [] // expose "messages" local variable - res.locals.messages = msgs; + res.locals.messages = msgs // expose "hasMessages" - res.locals.hasMessages = !! msgs.length; + res.locals.hasMessages = !!msgs.length /* This is equivalent: res.locals({ @@ -66,30 +66,30 @@ app.use(function(req, res, next){ }); */ - next(); + next() // empty or "flush" the messages so they // don't build up - req.session.messages = []; -}); + req.session.messages = [] +}) // load controllers -require('./lib/boot')(app, { verbose: !module.parent }); +require('./lib/boot')(app, { verbose: !module.parent }) -app.use(function(err, req, res, next){ +app.use((err, req, res, next) => { // log it - if (!module.parent) console.error(err.stack); + if (!module.parent) console.error(err.stack) // error page - res.status(500).render('5xx'); -}); + res.status(500).render('5xx') +}) // assume 404 since no middleware responded -app.use(function(req, res, next){ - res.status(404).render('404', { url: req.originalUrl }); -}); +app.use((req, res, next) => { + res.status(404).render('404', { url: req.originalUrl }) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/mvc/lib/boot.js b/examples/mvc/lib/boot.js index fc2ab0fad99..6932471f352 100644 --- a/examples/mvc/lib/boot.js +++ b/examples/mvc/lib/boot.js @@ -4,80 +4,81 @@ * Module dependencies. */ -var express = require('../../..'); -var fs = require('node:fs'); -var path = require('node:path'); +const express = require('../../../') +const fs = require('node:fs') +const path = require('node:path') -module.exports = function(parent, options){ - var dir = path.join(__dirname, '..', 'controllers'); - var verbose = options.verbose; - fs.readdirSync(dir).forEach(function(name){ - var file = path.join(dir, name) - if (!fs.statSync(file).isDirectory()) return; - verbose && console.log('\n %s:', name); - var obj = require(file); - var name = obj.name || name; - var prefix = obj.prefix || ''; - var app = express(); - var handler; - var method; - var url; +module.exports = function (parent, options) { + const dir = path.join(__dirname, '..', 'controllers') + const verbose = options.verbose + fs.readdirSync(dir).forEach((dirname) => { + const subdir = path.join(dir, dirname) + if (!fs.statSync(subdir).isDirectory()) return + verbose && console.log('\n %s:', dirname) + // eslint-disable-next-line global-require + const obj = require(subdir) + const name = obj.name || dirname + const prefix = obj.prefix || '' + const app = express() + let handler + let method + let url // allow specifying the view engine - if (obj.engine) app.set('view engine', obj.engine); - app.set('views', path.join(__dirname, '..', 'controllers', name, 'views')); + if (obj.engine) app.set('view engine', obj.engine) + app.set('views', path.join(__dirname, '..', 'controllers', name, 'views')) // generate routes based // on the exported methods - for (var key in obj) { + for (const key in obj) { // "reserved" exports - if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue; + if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue // route exports switch (key) { case 'show': - method = 'get'; - url = '/' + name + '/:' + name + '_id'; - break; + method = 'get' + url = '/' + name + '/:' + name + '_id' + break case 'list': - method = 'get'; - url = '/' + name + 's'; - break; + method = 'get' + url = '/' + name + 's' + break case 'edit': - method = 'get'; - url = '/' + name + '/:' + name + '_id/edit'; - break; + method = 'get' + url = '/' + name + '/:' + name + '_id/edit' + break case 'update': - method = 'put'; - url = '/' + name + '/:' + name + '_id'; - break; + method = 'put' + url = '/' + name + '/:' + name + '_id' + break case 'create': - method = 'post'; - url = '/' + name; - break; + method = 'post' + url = '/' + name + break case 'index': - method = 'get'; - url = '/'; - break; + method = 'get' + url = '/' + break default: /* istanbul ignore next */ - throw new Error('unrecognized route: ' + name + '.' + key); + throw new Error('unrecognized route: ' + name + '.' + key) } // setup - handler = obj[key]; - url = prefix + url; + handler = obj[key] + url = prefix + url // before middleware support if (obj.before) { - app[method](url, obj.before, handler); - verbose && console.log(' %s %s -> before -> %s', method.toUpperCase(), url, key); + app[method](url, obj.before, handler) + verbose && console.log(' %s %s -> before -> %s', method.toUpperCase(), url, key) } else { - app[method](url, handler); - verbose && console.log(' %s %s -> %s', method.toUpperCase(), url, key); + app[method](url, handler) + verbose && console.log(' %s %s -> %s', method.toUpperCase(), url, key) } } // mount the app - parent.use(app); - }); -}; + parent.use(app) + }) +} diff --git a/examples/online/index.js b/examples/online/index.js index 0b5fdffc86a..13e5b3dd071 100644 --- a/examples/online/index.js +++ b/examples/online/index.js @@ -11,51 +11,49 @@ * Module dependencies. */ -var express = require('../..'); -var online = require('online'); -var redis = require('redis'); -var db = redis.createClient(); +const express = require('../../') +let online = require('online') +const redis = require('redis') +const db = redis.createClient() // online -online = online(db); +online = online(db) // app -var app = express(); +const app = express() // 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, res, next) => { // fire-and-forget - online.add(req.headers['user-agent']); - next(); -}); + online.add(req.headers['user-agent']) + next() +}) /** * List helper. */ -function list(ids) { - return ''; +function list (ids) { + return '' } /** * GET users online. */ -app.get('/', function(req, res, next){ - online.last(5, function(err, ids){ - if (err) return next(err); - res.send('

Users online: ' + ids.length + '

' + list(ids)); - }); -}); +app.get('/', (req, res, next) => { + online.last(5, (err, ids) => { + if (err) return next(err) + res.send('

Users online: ' + ids.length + '

' + list(ids)) + }) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/params/index.js b/examples/params/index.js index 11eef51a592..d565ac5e373 100644 --- a/examples/params/index.js +++ b/examples/params/index.js @@ -4,71 +4,71 @@ * Module dependencies. */ -var createError = require('http-errors') -var express = require('../../'); -var app = module.exports = express(); +const createError = require('http-errors') +const express = require('../../') +const app = module.exports = express() // Faux database -var users = [ - { name: 'tj' } - , { name: 'tobi' } - , { name: 'loki' } - , { name: 'jane' } - , { name: 'bandit' } -]; +const users = [ + { name: 'tj' }, + { name: 'tobi' }, + { name: 'loki' }, + { name: 'jane' }, + { name: 'bandit' } +] // Convert :to and :from to integers -app.param(['to', 'from'], function(req, res, next, num, name){ - req.params[name] = parseInt(num, 10); - if( isNaN(req.params[name]) ){ - next(createError(400, 'failed to parseInt '+num)); +app.param(['to', 'from'], (req, res, next, num, name) => { + req.params[name] = parseInt(num, 10) + if (isNaN(req.params[name])) { + next(createError(400, 'failed to parseInt ' + num)) } else { - next(); + next() } -}); +}) // Load user by id -app.param('user', function(req, res, next, id){ +app.param('user', (req, res, next, id) => { req.user = users[id] if (req.user) { - next(); + next() } else { - next(createError(404, 'failed to find user')); + next(createError(404, 'failed to find user')) } -}); +}) /** * GET index. */ -app.get('/', function(req, res){ - res.send('Visit /user/0 or /users/0-2'); -}); +app.get('/', (req, res) => { + res.send('Visit /user/0 or /users/0-2') +}) /** * GET :user. */ -app.get('/user/:user', function (req, res) { - res.send('user ' + req.user.name); -}); +app.get('/user/:user', (req, res) => { + res.send('user ' + req.user.name) +}) /** * GET users :from - :to. */ -app.get('/users/:from-:to', function (req, res) { - var from = req.params.from; - var to = req.params.to; - var names = users.map(function(user){ return user.name; }); - res.send('users ' + names.slice(from, to + 1).join(', ')); -}); +app.get('/users/:from-:to', (req, res) => { + const from = req.params.from + const to = req.params.to + const names = users.map((user) => user.name) + res.send('users ' + names.slice(from, to + 1).join(', ')) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/resource/index.js b/examples/resource/index.js index 627ab24c5a2..bea4411843c 100644 --- a/examples/resource/index.js +++ b/examples/resource/index.js @@ -4,68 +4,65 @@ * Module dependencies. */ -var express = require('../../'); +const express = require('../../') -var app = module.exports = express(); +const app = module.exports = express() // Ad-hoc example resource method -app.resource = function(path, obj) { - this.get(path, obj.index); - this.get(path + '/:a..:b{.:format}', function(req, res){ - var a = parseInt(req.params.a, 10); - var b = parseInt(req.params.b, 10); - var format = req.params.format; - obj.range(req, res, a, b, format); - }); - this.get(path + '/:id', obj.show); - this.delete(path + '/:id', function(req, res){ - var id = parseInt(req.params.id, 10); - obj.destroy(req, res, id); - }); -}; +app.resource = function (path, obj) { + this.get(path, obj.index) + this.get(path + '/:a..:b{.:format}', (req, res) => { + const a = parseInt(req.params.a, 10) + const b = parseInt(req.params.b, 10) + const format = req.params.format + obj.range(req, res, a, b, format) + }) + this.get(path + '/:id', obj.show) + this.delete(path + '/:id', (req, res) => { + const id = parseInt(req.params.id, 10) + obj.destroy(req, res, id) + }) +} // Fake records -var users = [ - { name: 'tj' } - , { name: 'ciaran' } - , { name: 'aaron' } - , { name: 'guillermo' } - , { name: 'simon' } - , { name: 'tobi' } -]; +const users = [ + { name: 'tj' }, + { name: 'ciaran' }, + { name: 'aaron' }, + { name: 'guillermo' }, + { name: 'simon' }, + { name: 'tobi' } +] // Fake controller. -var User = { - index: function(req, res){ - res.send(users); +const User = { + index: function (req, res) { + res.send(users) }, - show: function(req, res){ - res.send(users[req.params.id] || { error: 'Cannot find user' }); + show: function (req, res) { + res.send(users[req.params.id] || { error: 'Cannot find user' }) }, - destroy: function(req, res, id){ - var destroyed = id in users; - delete users[id]; - res.send(destroyed ? 'destroyed' : 'Cannot find user'); + destroy: function (req, res, id) { + const destroyed = id in users + delete users[id] + res.send(destroyed ? 'destroyed' : 'Cannot find user') }, - range: function(req, res, a, b, format){ - var range = users.slice(a, b + 1); + range: function (req, res, a, b, format) { + const range = users.slice(a, b + 1) switch (format) { case 'json': - res.send(range); - break; + res.send(range) + break case 'html': default: - var html = ''; - res.send(html); - break; + res.send('') + break } } -}; +} // curl http://localhost:3000/users -- responds with all users // curl http://localhost:3000/users/1 -- responds with user 1 @@ -73,23 +70,23 @@ var User = { // curl http://localhost:3000/users/1..3 -- responds with several users // curl -X DELETE http://localhost:3000/users/1 -- deletes the user -app.resource('/users', User); +app.resource('/users', User) -app.get('/', function(req, res){ +app.get('/', (req, res) => { res.send([ - '

Examples:

' - ].join('\n')); -}); + '

Examples:

' + ].join('\n')) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/route-map/index.js b/examples/route-map/index.js index 2bc28bd4b26..71954772f0e 100644 --- a/examples/route-map/index.js +++ b/examples/route-map/index.js @@ -4,53 +4,53 @@ * Module dependencies. */ -var escapeHtml = require('escape-html') -var express = require('../../lib/express'); +const escapeHtml = require('escape-html') +const express = require('../../') -var verbose = process.env.NODE_ENV !== 'test' +const verbose = process.env.NODE_ENV !== 'test' -var app = module.exports = express(); +const app = module.exports = express() -app.map = function(a, route){ - route = route || ''; - for (var key in a) { +app.map = function (a, route) { + route = route || '' + for (const key in a) { switch (typeof a[key]) { // { '/path': { ... }} case 'object': - app.map(a[key], route + key); - break; + app.map(a[key], route + key) + break // get: function(){ ... } case 'function': - if (verbose) console.log('%s %s', key, route); - app[key](route, a[key]); - break; + if (verbose) console.log('%s %s', key, route) + app[key](route, a[key]) + break } } -}; +} -var users = { - list: function(req, res){ - res.send('user list'); +const users = { + list: function (req, res) { + res.send('user list') }, - get: function(req, res){ - res.send('user ' + escapeHtml(req.params.uid)) + get: function (req, res) { + res.send('user ' + escapeHtml(req.params.uid)) }, - delete: function(req, res){ - res.send('delete users'); + delete: function (req, res) { + res.send('delete users') } -}; +} -var pets = { - list: function(req, res){ +const pets = { + list: function (req, res) { res.send('user ' + escapeHtml(req.params.uid) + '\'s pets') }, - delete: function(req, res){ + delete: function (req, res) { res.send('delete ' + escapeHtml(req.params.uid) + '\'s pet ' + escapeHtml(req.params.pid)) } -}; +} app.map({ '/users': { @@ -66,10 +66,10 @@ app.map({ } } } -}); +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/route-middleware/index.js b/examples/route-middleware/index.js index 44ec13a95b8..d738f33e417 100644 --- a/examples/route-middleware/index.js +++ b/examples/route-middleware/index.js @@ -4,9 +4,9 @@ * Module dependencies. */ -var express = require('../../lib/express'); +const express = require('../../') -var app = express(); +const app = express() // Example requests: // curl http://localhost:3000/user/0 @@ -16,43 +16,43 @@ var app = express(); // curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) // Dummy users -var users = [ - { id: 0, name: 'tj', email: 'tj@vision-media.ca', role: 'member' } - , { id: 1, name: 'ciaran', email: 'ciaranj@gmail.com', role: 'member' } - , { id: 2, name: 'aaron', email: 'aaron.heckmann+github@gmail.com', role: 'admin' } -]; +const users = [ + { id: 0, name: 'tj', email: 'tj@vision-media.ca', role: 'member' }, + { id: 1, name: 'ciaran', email: 'ciaranj@gmail.com', role: 'member' }, + { id: 2, name: 'aaron', email: 'aaron.heckmann+github@gmail.com', role: 'admin' } +] -function loadUser(req, res, next) { +function loadUser (req, res, next) { // You would fetch your user from the db - var user = users[req.params.id]; + const user = users[req.params.id] if (user) { - req.user = user; - next(); + req.user = user + next() } else { - next(new Error('Failed to load user ' + req.params.id)); + next(new Error('Failed to load user ' + req.params.id)) } } -function andRestrictToSelf(req, res, next) { +function andRestrictToSelf (req, res, next) { // If our authenticated user is the user we are viewing // then everything is fine :) if (req.authenticatedUser.id === req.user.id) { - next(); + next() } else { // You may want to implement specific exceptions // such as UnauthorizedError or similar so that you // can handle these can be special-cased in an error handler // (view ./examples/pages for this) - next(new Error('Unauthorized')); + next(new Error('Unauthorized')) } } -function andRestrictTo(role) { - return function(req, res, next) { +function andRestrictTo (role) { + return function (req, res, next) { if (req.authenticatedUser.role === role) { - next(); + next() } else { - next(new Error('Unauthorized')); + next(new Error('Unauthorized')) } } } @@ -62,29 +62,29 @@ function andRestrictTo(role) { // but this illustrates how an authenticated user // may interact with middleware -app.use(function(req, res, next){ - req.authenticatedUser = users[0]; - next(); -}); +app.use((req, res, next) => { + req.authenticatedUser = users[0] + next() +}) -app.get('/', function(req, res){ - res.redirect('/user/0'); -}); +app.get('/', (req, res) => { + res.redirect('/user/0') +}) -app.get('/user/:id', loadUser, function(req, res){ - res.send('Viewing user ' + req.user.name); -}); +app.get('/user/:id', loadUser, (req, res) => { + res.send('Viewing user ' + req.user.name) +}) -app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){ - res.send('Editing user ' + req.user.name); -}); +app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req, res) => { + res.send('Editing user ' + req.user.name) +}) -app.delete('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){ - res.send('Deleted user ' + req.user.name); -}); +app.delete('/user/:id', loadUser, andRestrictTo('admin'), (req, res) => { + res.send('Deleted user ' + req.user.name) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/route-separation/index.js b/examples/route-separation/index.js index 0a29c9421a6..148d617cc1f 100644 --- a/examples/route-separation/index.js +++ b/examples/route-separation/index.js @@ -4,52 +4,52 @@ * Module dependencies. */ -var express = require('../..'); -var path = require('node:path'); -var app = express(); -var logger = require('morgan'); -var cookieParser = require('cookie-parser'); -var methodOverride = require('method-override'); -var site = require('./site'); -var post = require('./post'); -var user = require('./user'); - -module.exports = app; +const express = require('../../') +const path = require('node:path') +const app = express() +const logger = require('morgan') +const cookieParser = require('cookie-parser') +const methodOverride = require('method-override') +const site = require('./site') +const post = require('./post') +const user = require('./user') + +module.exports = app // Config -app.set('view engine', 'ejs'); -app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs') +app.set('views', path.join(__dirname, 'views')) /* istanbul ignore next */ if (!module.parent) { - app.use(logger('dev')); + app.use(logger('dev')) } -app.use(methodOverride('_method')); -app.use(cookieParser()); +app.use(methodOverride('_method')) +app.use(cookieParser()) app.use(express.urlencoded({ extended: true })) -app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'public'))) // General -app.get('/', site.index); +app.get('/', site.index) // User -app.get('/users', user.list); -app.all('/user/:id{/:op}', user.load); -app.get('/user/:id', user.view); -app.get('/user/:id/view', user.view); -app.get('/user/:id/edit', user.edit); -app.put('/user/:id/edit', user.update); +app.get('/users', user.list) +app.all('/user/:id{/:op}', user.load) +app.get('/user/:id', user.view) +app.get('/user/:id/view', user.view) +app.get('/user/:id/edit', user.edit) +app.put('/user/:id/edit', user.update) // Posts -app.get('/posts', post.list); +app.get('/posts', post.list) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/route-separation/post.js b/examples/route-separation/post.js index 3a8e3a2d225..19cd89137e2 100644 --- a/examples/route-separation/post.js +++ b/examples/route-separation/post.js @@ -2,12 +2,12 @@ // Fake posts database -var posts = [ +const posts = [ { title: 'Foo', body: 'some foo bar' }, { title: 'Foo bar', body: 'more foo bar' }, { title: 'Foo bar baz', body: 'more foo bar baz' } -]; +] -exports.list = function(req, res){ - res.render('posts', { title: 'Posts', posts: posts }); -}; +exports.list = function (req, res) { + res.render('posts', { title: 'Posts', posts }) +} diff --git a/examples/route-separation/site.js b/examples/route-separation/site.js index aee36d1bd72..ef4e8866645 100644 --- a/examples/route-separation/site.js +++ b/examples/route-separation/site.js @@ -1,5 +1,5 @@ 'use strict' -exports.index = function(req, res){ - res.render('index', { title: 'Route Separation Example' }); -}; +exports.index = function (req, res) { + res.render('index', { title: 'Route Separation Example' }) +} diff --git a/examples/route-separation/user.js b/examples/route-separation/user.js index bc6fbd7baf3..28b46c5e6cb 100644 --- a/examples/route-separation/user.js +++ b/examples/route-separation/user.js @@ -2,46 +2,46 @@ // Fake user database -var users = [ +const users = [ { name: 'TJ', email: 'tj@vision-media.ca' }, { name: 'Tobi', email: 'tobi@vision-media.ca' } -]; +] -exports.list = function(req, res){ - res.render('users', { title: 'Users', users: users }); -}; +exports.list = function (req, res) { + res.render('users', { title: 'Users', users }) +} -exports.load = function(req, res, next){ - var id = req.params.id; - req.user = users[id]; +exports.load = function (req, res, next) { + const id = req.params.id + req.user = users[id] if (req.user) { - next(); + next() } else { - var err = new Error('cannot find user ' + id); - err.status = 404; - next(err); + const err = new Error('cannot find user ' + id) + err.status = 404 + next(err) } -}; +} -exports.view = function(req, res){ +exports.view = function (req, res) { res.render('users/view', { title: 'Viewing user ' + req.user.name, user: req.user - }); -}; + }) +} -exports.edit = function(req, res){ +exports.edit = function (req, res) { res.render('users/edit', { title: 'Editing user ' + req.user.name, user: req.user - }); -}; + }) +} -exports.update = function(req, res){ +exports.update = function (req, res) { // Normally you would handle all kinds of // validation and save back to the db - var user = req.body.user; - req.user.name = user.name; - req.user.email = user.email; - res.redirect(req.get('Referrer') || '/'); -}; + const user = req.body.user + req.user.name = user.name + req.user.email = user.email + res.redirect(req.get('Referrer') || '/') +} diff --git a/examples/search/index.js b/examples/search/index.js index 951e0d440a6..3a9ca142500 100644 --- a/examples/search/index.js +++ b/examples/search/index.js @@ -11,37 +11,37 @@ * Module dependencies. */ -var express = require('../..'); -var path = require('node:path'); -var redis = require('redis'); +const express = require('../../') +const path = require('node:path') +const redis = require('redis') -var db = redis.createClient(); +const db = redis.createClient() // npm install redis -var app = express(); +const app = express() -app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'public'))) // populate search -db.sadd('ferret', 'tobi'); -db.sadd('ferret', 'loki'); -db.sadd('ferret', 'jane'); -db.sadd('cat', 'manny'); -db.sadd('cat', 'luna'); +db.sadd('ferret', 'tobi') +db.sadd('ferret', 'loki') +db.sadd('ferret', 'jane') +db.sadd('cat', 'manny') +db.sadd('cat', 'luna') /** * GET search for :query. */ -app.get('/search/:query?', function(req, res, next){ - var query = req.params.query; - db.smembers(query, function(err, vals){ - if (err) return next(err); - res.send(vals); - }); -}); +app.get('/search/:query?', (req, res, next) => { + const query = req.params.query + db.smembers(query, (err, vals) => { + if (err) return next(err) + res.send(vals) + }) +}) /** * GET client javascript. Here we use sendFile() @@ -50,12 +50,12 @@ app.get('/search/:query?', function(req, res, next){ * template. */ -app.get('/client.js', function(req, res){ - res.sendFile(path.join(__dirname, 'client.js')); -}); +app.get('/client.js', (req, res) => { + res.sendFile(path.join(__dirname, 'client.js')) +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/search/public/client.js b/examples/search/public/client.js index cd43faf71e0..4b73c0e1b95 100644 --- a/examples/search/public/client.js +++ b/examples/search/public/client.js @@ -1,15 +1,17 @@ 'use strict' -var search = document.querySelector('[type=search]'); -var code = document.querySelector('pre'); +const search = document.querySelector('[type=search]') +const code = document.querySelector('pre') -search.addEventListener('keyup', function(){ - var xhr = new XMLHttpRequest; - xhr.open('GET', '/search/' + search.value, true); - xhr.onreadystatechange = function(){ +/* global XMLHttpRequest */ + +search.addEventListener('keyup', () => { + const xhr = new XMLHttpRequest() + xhr.open('GET', '/search/' + search.value, true) + xhr.onreadystatechange = function () { if (xhr.readyState === 4) { - code.textContent = xhr.responseText; + code.textContent = xhr.responseText } - }; - xhr.send(); -}, false); + } + xhr.send() +}, false) diff --git a/examples/session/index.js b/examples/session/index.js index 2bb2b109c82..4d0a25c4ba5 100644 --- a/examples/session/index.js +++ b/examples/session/index.js @@ -7,31 +7,31 @@ // $ npm install redis // $ redis-server -var express = require('../..'); -var session = require('express-session'); +const express = require('../../') +const session = require('express-session') -var app = express(); +const app = express() // Populates req.session app.use(session({ resave: false, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'keyboard cat' -})); +})) -app.get('/', function(req, res){ - var body = ''; +app.get('/', (req, res) => { + let body = '' if (req.session.views) { - ++req.session.views; + ++req.session.views } else { - req.session.views = 1; - body += '

First time visiting? view this page in several browsers :)

'; + req.session.views = 1 + body += '

First time visiting? view this page in several browsers :)

' } - res.send(body + '

viewed ' + req.session.views + ' times.

'); -}); + res.send(body + '

viewed ' + req.session.views + ' times.

') +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/session/redis.js b/examples/session/redis.js index bbbdc7fd3e5..f967971db03 100644 --- a/examples/session/redis.js +++ b/examples/session/redis.js @@ -4,36 +4,36 @@ * Module dependencies. */ -var express = require('../..'); -var logger = require('morgan'); -var session = require('express-session'); +const express = require('../../') +const logger = require('morgan') +const session = require('express-session') // pass the express to the connect redis module // allowing it to inherit from session.Store -var RedisStore = require('connect-redis')(session); +const RedisStore = require('connect-redis')(session) -var app = express(); +const app = express() -app.use(logger('dev')); +app.use(logger('dev')) // Populates req.session app.use(session({ resave: false, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'keyboard cat', - store: new RedisStore -})); + store: new RedisStore() +})) -app.get('/', function(req, res){ - var body = ''; +app.get('/', (req, res) => { + let body = '' if (req.session.views) { - ++req.session.views; + ++req.session.views } else { - req.session.views = 1; - body += '

First time visiting? view this page in several browsers :)

'; + req.session.views = 1 + body += '

First time visiting? view this page in several browsers :)

' } - res.send(body + '

viewed ' + req.session.views + ' times.

'); -}); + res.send(body + '

viewed ' + req.session.views + ' times.

') +}) -app.listen(3000); -console.log('Express app started on port 3000'); +app.listen(3000) +console.log('Express app started on port 3000') diff --git a/examples/static-files/index.js b/examples/static-files/index.js index b7c697a2f9f..89540176bde 100644 --- a/examples/static-files/index.js +++ b/examples/static-files/index.js @@ -4,13 +4,13 @@ * Module dependencies. */ -var express = require('../..'); -var logger = require('morgan'); -var path = require('node:path'); -var app = express(); +const express = require('../../') +const logger = require('morgan') +const path = require('node:path') +const app = express() // log requests -app.use(logger('dev')); +app.use(logger('dev')) // express on its own has no notion // of a "file". The express.static() @@ -19,7 +19,7 @@ app.use(logger('dev')); // that you pass it. In this case "GET /js/app.js" // will look for "./public/js/app.js". -app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'public'))) // if you wanted to "prefix" you may use // the mounting feature of Connect, for example @@ -27,17 +27,17 @@ app.use(express.static(path.join(__dirname, 'public'))); // The mount-path "/static" is simply removed before // passing control to the express.static() middleware, // thus it serves the file correctly by ignoring "/static" -app.use('/static', express.static(path.join(__dirname, 'public'))); +app.use('/static', express.static(path.join(__dirname, 'public'))) // if for some reason you want to serve files from // several directories, you can use express.static() // multiple times! Here we're passing "./public/css", // this will allow "GET /style.css" instead of "GET /css/style.css": -app.use(express.static(path.join(__dirname, 'public', 'css'))); - -app.listen(3000); -console.log('listening on port 3000'); -console.log('try:'); -console.log(' GET /hello.txt'); -console.log(' GET /js/app.js'); -console.log(' GET /css/style.css'); +app.use(express.static(path.join(__dirname, 'public', 'css'))) + +app.listen(3000) +console.log('listening on port 3000') +console.log('try:') +console.log(' GET /hello.txt') +console.log(' GET /js/app.js') +console.log(' GET /css/style.css') diff --git a/examples/vhost/index.js b/examples/vhost/index.js index a9499356b42..d63400d953b 100644 --- a/examples/vhost/index.js +++ b/examples/vhost/index.js @@ -4,9 +4,9 @@ * Module dependencies. */ -var express = require('../..'); -var logger = require('morgan'); -var vhost = require('vhost'); +const express = require('../../') +const logger = require('morgan') +const vhost = require('vhost') /* edit /etc/hosts: @@ -18,36 +18,36 @@ edit /etc/hosts: // Main server app -var main = express(); +const main = express() -if (!module.parent) main.use(logger('dev')); +if (!module.parent) main.use(logger('dev')) -main.get('/', function(req, res){ - res.send('Hello from main app!'); -}); +main.get('/', (req, res) => { + res.send('Hello from main app!') +}) -main.get('/:sub', function(req, res){ - res.send('requested ' + req.params.sub); -}); +main.get('/:sub', (req, res) => { + res.send('requested ' + req.params.sub) +}) // Redirect app -var redirect = express(); +const redirect = express() -redirect.use(function(req, res){ - if (!module.parent) console.log(req.vhost); - res.redirect('http://example.com:3000/' + req.vhost[0]); -}); +redirect.use((req, res) => { + if (!module.parent) console.log(req.vhost) + res.redirect('http://example.com:3000/' + req.vhost[0]) +}) // Vhost app -var app = module.exports = express(); +const app = module.exports = express() -app.use(vhost('*.example.com', redirect)); // Serves all subdomains via Redirect app -app.use(vhost('example.com', main)); // Serves top level domain via Main server app +app.use(vhost('*.example.com', redirect)) // Serves all subdomains via Redirect app +app.use(vhost('example.com', main)) // Serves top level domain via Main server app /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/view-constructor/github-view.js b/examples/view-constructor/github-view.js index eabfb2d0c18..58bb92adfdf 100644 --- a/examples/view-constructor/github-view.js +++ b/examples/view-constructor/github-view.js @@ -4,15 +4,15 @@ * Module dependencies. */ -var https = require('node:https'); -var path = require('node:path'); -var extname = path.extname; +const https = require('node:https') +const path = require('node:path') +const extname = path.extname /** * Expose `GithubView`. */ -module.exports = GithubView; +module.exports = GithubView /** * Custom view that fetches and renders @@ -20,34 +20,34 @@ module.exports = GithubView; * render templates from a database etc. */ -function GithubView(name, options){ - this.name = name; - options = options || {}; - this.engine = options.engines[extname(name)]; +function GithubView (name, options) { + this.name = name + options = options || {} + this.engine = options.engines[extname(name)] // "root" is the app.set('views') setting, however // in your own implementation you could ignore this - this.path = '/' + options.root + '/master/' + name; + this.path = '/' + options.root + '/master/' + name } /** * Render the view. */ -GithubView.prototype.render = function(options, fn){ - var self = this; - var opts = { +GithubView.prototype.render = function (options, fn) { + const self = this + const opts = { host: 'raw.githubusercontent.com', port: 443, path: this.path, method: 'GET' - }; - - https.request(opts, function(res) { - var buf = ''; - res.setEncoding('utf8'); - res.on('data', function(str){ buf += str }); - res.on('end', function(){ - self.engine(buf, options, fn); - }); - }).end(); -}; + } + + https.request(opts, (res) => { + let buf = '' + res.setEncoding('utf8') + res.on('data', (str) => { buf += str }) + res.on('end', () => { + self.engine(buf, options, fn) + }) + }).end() +} diff --git a/examples/view-constructor/index.js b/examples/view-constructor/index.js index 3d673670e31..bde51f89b1a 100644 --- a/examples/view-constructor/index.js +++ b/examples/view-constructor/index.js @@ -4,45 +4,43 @@ * Module dependencies. */ -var express = require('../../'); -var GithubView = require('./github-view'); -var md = require('marked').parse; +const express = require('../../') +const GithubView = require('./github-view') +const md = require('marked').parse -var app = module.exports = express(); +const app = module.exports = express() // register .md as an engine in express view system -app.engine('md', function(str, options, fn){ +app.engine('md', (str, options, fn) => { try { - var html = md(str); - html = html.replace(/\{([^}]+)\}/g, function(_, name){ - return options[name] || ''; - }); - fn(null, html); - } catch(err) { - fn(err); + let html = md(str) + html = html.replace(/\{([^}]+)\}/g, (_, name) => options[name] || '') + fn(null, html) + } catch (err) { + fn(err) } -}); +}) // pointing to a particular github repo to load files from it -app.set('views', 'expressjs/express'); +app.set('views', 'expressjs/express') // register a new view constructor -app.set('view', GithubView); +app.set('view', GithubView) -app.get('/', function(req, res){ +app.get('/', (req, res) => { // rendering a view relative to the repo. // app.locals, res.locals, and locals passed // work like they normally would - res.render('examples/markdown/views/index.md', { title: 'Example' }); -}); + res.render('examples/markdown/views/index.md', { title: 'Example' }) +}) -app.get('/Readme.md', function(req, res){ +app.get('/Readme.md', (req, res) => { // rendering a view from https://github.com/expressjs/express/blob/master/Readme.md - res.render('Readme.md'); -}); + res.render('Readme.md') +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/view-locals/index.js b/examples/view-locals/index.js index e6355602d4e..f48fdbf257a 100644 --- a/examples/view-locals/index.js +++ b/examples/view-locals/index.js @@ -4,17 +4,17 @@ * Module dependencies. */ -var express = require('../..'); -var path = require('node:path'); -var User = require('./user'); -var app = express(); +const express = require('../../') +const path = require('node:path') +const User = require('./user') +const app = express() -app.set('views', path.join(__dirname, 'views')); -app.set('view engine', 'ejs'); +app.set('views', path.join(__dirname, 'views')) +app.set('view engine', 'ejs') // filter ferrets only -function ferrets(user) { +function ferrets (user) { return user.species === 'ferret' } @@ -23,54 +23,48 @@ function ferrets(user) { // in order to expose the "count" // and "users" locals -app.get('/', function(req, res, next){ - User.count(function(err, count){ - if (err) return next(err); - User.all(function(err, users){ - if (err) return next(err); +app.get('/', (req, res, next) => { + User.count((err, count) => { + if (err) return next(err) + User.all((err, users) => { + if (err) return next(err) res.render('index', { title: 'Users', - count: count, + count, users: users.filter(ferrets) - }); + }) }) }) -}); - - - +}) // this approach is cleaner, // less nesting and we have // the variables available // on the request object -function count(req, res, next) { - User.count(function(err, count){ - if (err) return next(err); - req.count = count; - next(); +function count (req, res, next) { + User.count((err, count) => { + if (err) return next(err) + req.count = count + next() }) } -function users(req, res, next) { - User.all(function(err, users){ - if (err) return next(err); - req.users = users; - next(); +function users (req, res, next) { + User.all((err, users) => { + if (err) return next(err) + req.users = users + next() }) } -app.get('/middleware', count, users, function (req, res) { +app.get('/middleware', count, users, (req, res) => { res.render('index', { title: 'Users', count: req.count, users: req.users.filter(ferrets) - }); -}); - - - + }) +}) // this approach is much like the last // however we're explicitly exposing @@ -83,29 +77,29 @@ app.get('/middleware', count, users, function (req, res) { // so in that sense the previous example // is more flexible with `req.users`. -function count2(req, res, next) { - User.count(function(err, count){ - if (err) return next(err); - res.locals.count = count; - next(); +function count2 (req, res, next) { + User.count((err, count) => { + if (err) return next(err) + res.locals.count = count + next() }) } -function users2(req, res, next) { - User.all(function(err, users){ - if (err) return next(err); - res.locals.users = users.filter(ferrets); - next(); +function users2 (req, res, next) { + User.all((err, users) => { + if (err) return next(err) + res.locals.users = users.filter(ferrets) + next() }) } -app.get('/middleware-locals', count2, users2, function (req, res) { +app.get('/middleware-locals', count2, users2, (req, res) => { // you can see now how we have much less // to pass to res.render(). If we have // several routes related to users this // can be a great productivity booster - res.render('index', { title: 'Users' }); -}); + res.render('index', { title: 'Users' }) +}) // keep in mind that middleware may be placed anywhere // and in various combinations, so if you have locals @@ -150,6 +144,6 @@ app.all('/api/*', function(req, res, next){ /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/examples/view-locals/user.js b/examples/view-locals/user.js index aaa6f85ff0e..6f29020f4aa 100644 --- a/examples/view-locals/user.js +++ b/examples/view-locals/user.js @@ -1,36 +1,36 @@ 'use strict' -module.exports = User; +module.exports = User // faux model -function User(name, age, species) { - this.name = name; - this.age = age; - this.species = species; +function User (name, age, species) { + this.name = name + this.age = age + this.species = species } -User.all = function(fn){ +User.all = function (fn) { // process.nextTick makes sure this function API // behaves in an asynchronous manner, like if it // was a real DB query to read all users. - process.nextTick(function(){ - fn(null, users); - }); -}; + process.nextTick(() => { + fn(null, users) + }) +} -User.count = function(fn){ - process.nextTick(function(){ - fn(null, users.length); - }); -}; +User.count = function (fn) { + process.nextTick(() => { + fn(null, users.length) + }) +} // faux database -var users = []; +const users = [] -users.push(new User('Tobi', 2, 'ferret')); -users.push(new User('Loki', 1, 'ferret')); -users.push(new User('Jane', 6, 'ferret')); -users.push(new User('Luna', 1, 'cat')); -users.push(new User('Manny', 1, 'cat')); +users.push(new User('Tobi', 2, 'ferret')) +users.push(new User('Loki', 1, 'ferret')) +users.push(new User('Jane', 6, 'ferret')) +users.push(new User('Luna', 1, 'cat')) +users.push(new User('Manny', 1, 'cat')) diff --git a/examples/web-service/index.js b/examples/web-service/index.js index d1a90362153..b7c18601353 100644 --- a/examples/web-service/index.js +++ b/examples/web-service/index.js @@ -4,18 +4,18 @@ * Module dependencies. */ -var express = require('../../'); +const express = require('../../') -var app = module.exports = express(); +const app = module.exports = express() // create an error with .status. we // can then use the property in our // custom error handler (Connect respects this prop as well) -function error(status, msg) { - var err = new Error(msg); - err.status = status; - return err; +function error (status, msg) { + const err = new Error(msg) + err.status = status + return err } // if we wanted to supply more than JSON, we could @@ -27,91 +27,91 @@ function error(status, msg) { // meaning only paths prefixed with "/api" // will cause this middleware to be invoked -app.use('/api', function(req, res, next){ - var key = req.query['api-key']; +app.use('/api', (req, res, next) => { + const key = req.query['api-key'] // key isn't present - if (!key) return next(error(400, 'api key required')); + if (!key) return next(error(400, 'api key required')) // key is invalid if (apiKeys.indexOf(key) === -1) return next(error(401, 'invalid api key')) // all good, store req.key for route access - req.key = key; - next(); -}); + req.key = key + next() +}) // map of valid api keys, typically mapped to // account info with some sort of database like redis. // api keys do _not_ serve as authentication, merely to // track API usage or help prevent malicious behavior etc. -var apiKeys = ['foo', 'bar', 'baz']; +const apiKeys = ['foo', 'bar', 'baz'] // these two objects will serve as our faux database -var repos = [ +const repos = [ { name: 'express', url: 'https://github.com/expressjs/express' }, { name: 'stylus', url: 'https://github.com/learnboost/stylus' }, { name: 'cluster', url: 'https://github.com/learnboost/cluster' } -]; - -var users = [ - { name: 'tobi' } - , { name: 'loki' } - , { name: 'jane' } -]; - -var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] -}; +] + +const users = [ + { name: 'tobi' }, + { name: 'loki' }, + { name: 'jane' } +] + +const userRepos = { + tobi: [repos[0], repos[1]], + loki: [repos[1]], + jane: [repos[2]] +} // we now can assume the api key is valid, // and simply expose the data // example: http://localhost:3000/api/users/?api-key=foo -app.get('/api/users', function (req, res) { - res.send(users); -}); +app.get('/api/users', (req, res) => { + res.send(users) +}) // example: http://localhost:3000/api/repos/?api-key=foo -app.get('/api/repos', function (req, res) { - res.send(repos); -}); +app.get('/api/repos', (req, res) => { + res.send(repos) +}) // example: http://localhost:3000/api/user/tobi/repos/?api-key=foo -app.get('/api/user/:name/repos', function(req, res, next){ - var name = req.params.name; - var user = userRepos[name]; +app.get('/api/user/:name/repos', (req, res, next) => { + const name = req.params.name + const user = userRepos[name] - if (user) res.send(user); - else next(); -}); + if (user) res.send(user) + else next() +}) // middleware with an arity of 4 are considered // error handling middleware. When you next(err) // 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, next) => { // whatever you want here, feel free to populate // properties on `err` to treat it differently in here. - res.status(err.status || 500); - res.send({ error: err.message }); -}); + res.status(err.status || 500) + res.send({ error: err.message }) +}) // 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){ - res.status(404); +app.use((req, res) => { + res.status(404) res.send({ error: "Sorry, can't find that" }) -}); +}) /* istanbul ignore next */ if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); + app.listen(3000) + console.log('Express started on port 3000') } diff --git a/index.js b/index.js index d219b0c878d..9ae72fdf117 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,6 @@ * MIT Licensed */ -'use strict'; +'use strict' -module.exports = require('./lib/express'); +module.exports = require('./lib/express') diff --git a/lib/application.js b/lib/application.js index 838b882aaae..2a2a5e40c25 100644 --- a/lib/application.js +++ b/lib/application.js @@ -6,45 +6,42 @@ * MIT Licensed */ -'use strict'; +'use strict' /** * Module dependencies. * @private */ -var finalhandler = require('finalhandler'); -var debug = require('debug')('express:application'); -var View = require('./view'); -var http = require('node:http'); -var methods = require('./utils').methods; -var compileETag = require('./utils').compileETag; -var compileQueryParser = require('./utils').compileQueryParser; -var compileTrust = require('./utils').compileTrust; -var resolve = require('node:path').resolve; -var once = require('once') -var Router = require('router'); +const finalhandler = require('finalhandler') +const debug = require('debug')('express:application') +const View = require('./view') +const http = require('node:http') +const { methods, compileETag, compileQueryParser, compileTrust } = require('./utils') +const resolve = require('node:path').resolve +const once = require('once') +const Router = require('router') /** * Module variables. * @private */ -var slice = Array.prototype.slice; -var flatten = Array.prototype.flat; +const slice = Array.prototype.slice +const flatten = Array.prototype.flat /** * Application prototype. */ -var app = exports = module.exports = {}; +const app = exports = module.exports = {} /** * Variable for trust proxy inheritance back-compat * @private */ -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; +const trustProxyDefaultSymbol = '@@symbol:trust_proxy_default' /** * Initialize the server. @@ -56,62 +53,62 @@ var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; * @private */ -app.init = function init() { - var router = null; +app.init = function init () { + let router = null - this.cache = Object.create(null); - this.engines = Object.create(null); - this.settings = Object.create(null); + this.cache = Object.create(null) + this.engines = Object.create(null) + this.settings = Object.create(null) - this.defaultConfiguration(); + this.defaultConfiguration() // Setup getting to lazily add base router Object.defineProperty(this, 'router', { configurable: true, enumerable: true, - get: function getrouter() { + get: function getrouter () { if (router === null) { router = new Router({ caseSensitive: this.enabled('case sensitive routing'), strict: this.enabled('strict routing') - }); + }) } - return router; + return router } - }); -}; + }) +} /** * Initialize application configuration. * @private */ -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; +app.defaultConfiguration = function defaultConfiguration () { + const env = process.env.NODE_ENV || 'development' // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); + this.enable('x-powered-by') + this.set('etag', 'weak') + this.set('env', env) this.set('query parser', 'simple') - this.set('subdomain offset', 2); - this.set('trust proxy', false); + this.set('subdomain offset', 2) + this.set('trust proxy', false) // trust proxy inherit back-compat Object.defineProperty(this.settings, trustProxyDefaultSymbol, { configurable: true, value: true - }); + }) - debug('booting in %s mode', env); + debug('booting in %s mode', env) - this.on('mount', function onmount(parent) { + this.on('mount', function onmount (parent) { // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; + if (this.settings[trustProxyDefaultSymbol] === true && + typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy'] + delete this.settings['trust proxy fn'] } // inherit protos @@ -119,26 +116,26 @@ app.defaultConfiguration = function defaultConfiguration() { Object.setPrototypeOf(this.response, parent.response) Object.setPrototypeOf(this.engines, parent.engines) Object.setPrototypeOf(this.settings, parent.settings) - }); + }) // setup locals - this.locals = Object.create(null); + this.locals = Object.create(null) // top-most app is mounted at / - this.mountpath = '/'; + this.mountpath = '/' // default locals - this.locals.settings = this.settings; + this.locals.settings = this.settings // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); + this.set('view', View) + this.set('views', resolve('views')) + this.set('jsonp callback name', 'callback') if (env === 'production') { - this.enable('view cache'); + this.enable('view cache') } -}; +} /** * Dispatch a req, res pair into the application. Starts pipeline processing. @@ -149,21 +146,21 @@ app.defaultConfiguration = function defaultConfiguration() { * @private */ -app.handle = function handle(req, res, callback) { +app.handle = function handle (req, res, callback) { // final handler - var done = callback || finalhandler(req, res, { + const done = callback || finalhandler(req, res, { env: this.get('env'), onerror: logerror.bind(this) - }); + }) // set powered by header if (this.enabled('x-powered-by')) { - res.setHeader('X-Powered-By', 'Express'); + res.setHeader('X-Powered-By', 'Express') } // set circular references - req.res = res; - res.req = req; + req.res = res + res.req = req // alter the prototypes Object.setPrototypeOf(req, this.request) @@ -171,11 +168,11 @@ app.handle = function handle(req, res, callback) { // setup locals if (!res.locals) { - res.locals = Object.create(null); + res.locals = Object.create(null) } - this.router.handle(req, res, done); -}; + this.router.handle(req, res, done) +} /** * Proxy `Router#use()` to add middleware to the app router. @@ -187,61 +184,61 @@ app.handle = function handle(req, res, callback) { * @public */ -app.use = function use(fn) { - var offset = 0; - var path = '/'; +app.use = function use (fn) { + let offset = 0 + let path = '/' // default path to '/' // disambiguate app.use([fn]) if (typeof fn !== 'function') { - var arg = fn; + let arg = fn while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; + arg = arg[0] } // first arg is the path if (typeof arg !== 'function') { - offset = 1; - path = fn; + offset = 1 + path = fn } } - var fns = flatten.call(slice.call(arguments, offset), Infinity); + const fns = flatten.call(slice.call(arguments, offset), Infinity) if (fns.length === 0) { throw new TypeError('app.use() requires a middleware function') } // get router - var router = this.router; + const router = this.router fns.forEach(function (fn) { // non-express app if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); + return router.use(path, fn) } - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; + debug('.use app under %s', path) + fn.mountpath = path + fn.parent = this // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { + router.use(path, function mountedApp (req, res, next) { + const orig = req.app + fn.handle(req, res, (err) => { Object.setPrototypeOf(req, orig.request) Object.setPrototypeOf(res, orig.response) - next(err); - }); - }); + next(err) + }) + }) // mounted an app - fn.emit('mount', this); - }, this); + fn.emit('mount', this) + }, this) - return this; -}; + return this +} /** * Proxy to the app `Router#route()` @@ -253,9 +250,9 @@ app.use = function use(fn) { * @public */ -app.route = function route(path) { - return this.router.route(path); -}; +app.route = function route (path) { + return this.router.route(path) +} /** * Register the given template engine callback `fn` @@ -291,21 +288,21 @@ app.route = function route(path) { * @public */ -app.engine = function engine(ext, fn) { +app.engine = function engine (ext, fn) { if (typeof fn !== 'function') { - throw new Error('callback function required'); + throw new Error('callback function required') } // get file extension - var extension = ext[0] !== '.' + const extension = ext[0] !== '.' ? '.' + ext - : ext; + : ext // store engine - this.engines[extension] = fn; + this.engines[extension] = fn - return this; -}; + return this +} /** * Proxy to `Router#param()` with one added api feature. The _name_ parameter @@ -319,19 +316,19 @@ app.engine = function engine(ext, fn) { * @public */ -app.param = function param(name, fn) { +app.param = function param (name, fn) { if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); + for (let i = 0; i < name.length; i++) { + this.param(name[i], fn) } - return this; + return this } - this.router.param(name, fn); + this.router.param(name, fn) - return this; -}; + return this +} /** * Assign `setting` to `val`, or return `setting`'s value. @@ -348,39 +345,39 @@ app.param = function param(name, fn) { * @public */ -app.set = function set(setting, val) { +app.set = function set (setting, val) { if (arguments.length === 1) { // app.get(setting) - return this.settings[setting]; + return this.settings[setting] } - debug('set "%s" to %o', setting, val); + debug('set "%s" to %o', setting, val) // set value - this.settings[setting] = val; + this.settings[setting] = val // trigger matched settings switch (setting) { case 'etag': - this.set('etag fn', compileETag(val)); - break; + this.set('etag fn', compileETag(val)) + break case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; + this.set('query parser fn', compileQueryParser(val)) + break case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); + this.set('trust proxy fn', compileTrust(val)) // trust proxy inherit back-compat Object.defineProperty(this.settings, trustProxyDefaultSymbol, { configurable: true, value: false - }); + }) - break; + break } - return this; -}; + return this +} /** * Return the app's absolute pathname @@ -396,11 +393,11 @@ app.set = function set(setting, val) { * @private */ -app.path = function path() { +app.path = function path () { return this.parent ? this.parent.path() + this.mountpath - : ''; -}; + : '' +} /** * Check if `setting` is enabled (truthy). @@ -417,9 +414,9 @@ app.path = function path() { * @public */ -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; +app.enabled = function enabled (setting) { + return Boolean(this.set(setting)) +} /** * Check if `setting` is disabled. @@ -436,9 +433,9 @@ app.enabled = function enabled(setting) { * @public */ -app.disabled = function disabled(setting) { - return !this.set(setting); -}; +app.disabled = function disabled (setting) { + return !this.set(setting) +} /** * Enable `setting`. @@ -448,9 +445,9 @@ app.disabled = function disabled(setting) { * @public */ -app.enable = function enable(setting) { - return this.set(setting, true); -}; +app.enable = function enable (setting) { + return this.set(setting, true) +} /** * Disable `setting`. @@ -460,26 +457,26 @@ app.enable = function enable(setting) { * @public */ -app.disable = function disable(setting) { - return this.set(setting, false); -}; +app.disable = function disable (setting) { + return this.set(setting, false) +} /** * Delegate `.VERB(...)` calls to `router.VERB(...)`. */ -methods.forEach(function (method) { +methods.forEach((method) => { app[method] = function (path) { if (method === 'get' && arguments.length === 1) { // app.get(setting) - return this.set(path); + return this.set(path) } - var route = this.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); + const route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)) + return this + } +}) /** * Special-cased "all" method, applying the given route `path`, @@ -491,16 +488,16 @@ methods.forEach(function (method) { * @public */ -app.all = function all(path) { - var route = this.route(path); - var args = slice.call(arguments, 1); +app.all = function all (path) { + const route = this.route(path) + const args = slice.call(arguments, 1) - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); + for (let i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args) } - return this; -}; + return this +} /** * Render the given view `name` name with `options` @@ -519,60 +516,60 @@ app.all = function all(path) { * @public */ -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var view; +app.render = function render (name, options, callback) { + const cache = this.cache + let done = callback + const engines = this.engines + let opts = options + let view // support callback function as second arg if (typeof options === 'function') { - done = options; - opts = {}; + done = options + opts = {} } // merge options - var renderOptions = { ...this.locals, ...opts._locals, ...opts }; + const renderOptions = { ...this.locals, ...opts._locals, ...opts } // set .cache unless explicitly provided if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); + renderOptions.cache = this.enabled('view cache') } // primed cache if (renderOptions.cache) { - view = cache[name]; + view = cache[name] } // view if (!view) { - var View = this.get('view'); + const View = this.get('view') view = new View(name, { defaultEngine: this.get('view engine'), root: this.get('views'), - engines: engines - }); + engines + }) if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 + const dirs = Array.isArray(view.root) && view.root.length > 1 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); + const err = new Error('Failed to lookup view "' + name + '" in views ' + dirs) + err.view = view + return done(err) } // prime the cache if (renderOptions.cache) { - cache[name] = view; + cache[name] = view } } // render - tryRender(view, renderOptions, done); -}; + tryRender(view, renderOptions, done) +} /** * Listen for connections. @@ -595,11 +592,11 @@ app.render = function render(name, options, callback) { * @public */ -app.listen = function listen() { - var server = http.createServer(this) - var args = slice.call(arguments) +app.listen = function listen () { + const server = http.createServer(this) + const args = slice.call(arguments) if (typeof args[args.length - 1] === 'function') { - var done = args[args.length - 1] = once(args[args.length - 1]) + const done = args[args.length - 1] = once(args[args.length - 1]) server.once('error', done) } return server.listen.apply(server, args) @@ -612,9 +609,9 @@ app.listen = function listen() { * @private */ -function logerror(err) { +function logerror (err) { /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); + if (this.get('env') !== 'test') console.error(err.stack || err.toString()) } /** @@ -622,10 +619,10 @@ function logerror(err) { * @private */ -function tryRender(view, options, callback) { +function tryRender (view, options, callback) { try { - view.render(options, callback); + view.render(options, callback) } catch (err) { - callback(err); + callback(err) } } diff --git a/lib/express.js b/lib/express.js index 2d502eb54e4..43a1b0b280c 100644 --- a/lib/express.js +++ b/lib/express.js @@ -6,25 +6,25 @@ * MIT Licensed */ -'use strict'; +'use strict' /** * Module dependencies. */ -var bodyParser = require('body-parser') -var EventEmitter = require('node:events').EventEmitter; -var mixin = require('merge-descriptors'); -var proto = require('./application'); -var Router = require('router'); -var req = require('./request'); -var res = require('./response'); +const bodyParser = require('body-parser') +const { EventEmitter } = require('node:events') +const mixin = require('merge-descriptors') +const proto = require('./application') +const Router = require('router') +const req = require('./request') +const res = require('./response') /** * Expose `createApplication()`. */ -exports = module.exports = createApplication; +exports = module.exports = createApplication /** * Create an express application. @@ -33,13 +33,13 @@ exports = module.exports = createApplication; * @api public */ -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; +function createApplication () { + const app = function (req, res, next) { + app.handle(req, res, next) + } - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); + mixin(app, EventEmitter.prototype, false) + mixin(app, proto, false) // expose the prototype that will get set on requests app.request = Object.create(req, { @@ -51,24 +51,24 @@ function createApplication() { app: { configurable: true, enumerable: true, writable: true, value: app } }) - app.init(); - return app; + app.init() + return app } /** * Expose the prototypes. */ -exports.application = proto; -exports.request = req; -exports.response = res; +exports.application = proto +exports.request = req +exports.response = res /** * Expose constructors. */ -exports.Route = Router.Route; -exports.Router = Router; +exports.Route = Router.Route +exports.Router = Router /** * Expose middleware @@ -76,6 +76,6 @@ exports.Router = Router; exports.json = bodyParser.json exports.raw = bodyParser.raw -exports.static = require('serve-static'); +exports.static = require('serve-static') exports.text = bodyParser.text exports.urlencoded = bodyParser.urlencoded diff --git a/lib/request.js b/lib/request.js index 69990da39b6..369bf34e966 100644 --- a/lib/request.js +++ b/lib/request.js @@ -6,28 +6,28 @@ * MIT Licensed */ -'use strict'; +'use strict' /** * Module dependencies. * @private */ -var accepts = require('accepts'); -var isIP = require('node:net').isIP; -var typeis = require('type-is'); -var http = require('node:http'); -var fresh = require('fresh'); -var parseRange = require('range-parser'); -var parse = require('parseurl'); -var proxyaddr = require('proxy-addr'); +const accepts = require('accepts') +const { isIP } = require('node:net') +const typeis = require('type-is') +const http = require('node:http') +const fresh = require('fresh') +const parseRange = require('range-parser') +const parse = require('parseurl') +const proxyaddr = require('proxy-addr') /** * Request prototype. * @public */ -var req = Object.create(http.IncomingMessage.prototype) +const req = Object.create(http.IncomingMessage.prototype) /** * Module exports. @@ -61,26 +61,26 @@ module.exports = req */ req.get = -req.header = function header(name) { +req.header = function header (name) { if (!name) { - throw new TypeError('name argument is required to req.get'); + throw new TypeError('name argument is required to req.get') } if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); + throw new TypeError('name must be a string to req.get') } - var lc = name.toLowerCase(); + const lc = name.toLowerCase() switch (lc) { case 'referer': case 'referrer': - return this.headers.referrer - || this.headers.referer; + return this.headers.referrer || + this.headers.referer default: - return this.headers[lc]; + return this.headers[lc] } -}; +} /** * To do: update docs. @@ -128,10 +128,10 @@ req.header = function header(name) { * @public */ -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; +req.accepts = function () { + const accept = accepts(this) + return accept.types.apply(accept, arguments) +} /** * Check if the given `encoding`s are accepted. @@ -141,10 +141,10 @@ req.accepts = function(){ * @public */ -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; +req.acceptsEncodings = function () { + const accept = accepts(this) + return accept.encodings.apply(accept, arguments) +} /** * Check if the given `charset`s are acceptable, @@ -155,10 +155,10 @@ req.acceptsEncodings = function(){ * @public */ -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; +req.acceptsCharsets = function () { + const accept = accepts(this) + return accept.charsets.apply(accept, arguments) +} /** * Check if the given `lang`s are acceptable, @@ -169,9 +169,9 @@ req.acceptsCharsets = function(){ * @public */ -req.acceptsLanguages = function(...languages) { - return accepts(this).languages(...languages); -}; +req.acceptsLanguages = function (...languages) { + return accepts(this).languages(...languages) +} /** * Parse Range header field, capping to the given `size`. @@ -198,11 +198,11 @@ req.acceptsLanguages = function(...languages) { * @public */ -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; +req.range = function range (size, options) { + const range = this.get('Range') + if (!range) return + return parseRange(size, range, options) +} /** * Parse the query string of `req.url`. @@ -214,18 +214,18 @@ req.range = function range(size, options) { * @api public */ -defineGetter(req, 'query', function query(){ - var queryparse = this.app.get('query parser fn'); +defineGetter(req, 'query', function query () { + const queryparse = this.app.get('query parser fn') if (!queryparse) { // parsing is disabled - return Object.create(null); + return Object.create(null) } - var querystring = parse(this).query; + const querystring = parse(this).query - return queryparse(querystring); -}); + return queryparse(querystring) +}) /** * Check if the incoming request contains the "Content-Type" @@ -253,19 +253,19 @@ defineGetter(req, 'query', function query(){ * @public */ -req.is = function is(types) { - var arr = types; +req.is = function is (types) { + let arr = types // support flattened arguments if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; + arr = new Array(arguments.length) + for (let i = 0; i < arr.length; i++) { + arr[i] = arguments[i] } } - return typeis(this, arr); -}; + return typeis(this, arr) +} /** * Return the protocol string "http" or "https" @@ -281,25 +281,25 @@ req.is = function is(types) { * @public */ -defineGetter(req, 'protocol', function protocol(){ - var proto = this.socket.encrypted +defineGetter(req, 'protocol', function protocol () { + const proto = this.socket.encrypted ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); + : 'http' + const trust = this.app.get('trust proxy fn') if (!trust(this.socket.remoteAddress, 0)) { - return proto; + return proto } // Note: X-Forwarded-Proto is normally only ever a // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') + const header = this.get('X-Forwarded-Proto') || proto + const index = header.indexOf(',') return index !== -1 ? header.substring(0, index).trim() : header.trim() -}); +}) /** * Short-hand for: @@ -310,9 +310,9 @@ defineGetter(req, 'protocol', function protocol(){ * @public */ -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); +defineGetter(req, 'secure', function secure () { + return this.protocol === 'https' +}) /** * Return the remote address from the trusted proxy. @@ -324,10 +324,10 @@ defineGetter(req, 'secure', function secure(){ * @public */ -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); +defineGetter(req, 'ip', function ip () { + const trust = this.app.get('trust proxy fn') + return proxyaddr(this, trust) +}) /** * When "trust proxy" is set, trusted proxy addresses + client. @@ -341,16 +341,16 @@ defineGetter(req, 'ip', function ip(){ * @public */ -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); +defineGetter(req, 'ips', function ips () { + const trust = this.app.get('trust proxy fn') + const addrs = proxyaddr.all(this, trust) // reverse the order (to farthest -> closest) // and remove socket address addrs.reverse().pop() return addrs -}); +}) /** * Return subdomains as an array. @@ -367,18 +367,18 @@ defineGetter(req, 'ips', function ips() { * @public */ -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; +defineGetter(req, 'subdomains', function subdomains () { + const hostname = this.hostname - if (!hostname) return []; + if (!hostname) return [] - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) + const offset = this.app.get('subdomain offset') + const subdomains = !isIP(hostname) ? hostname.split('.').reverse() - : [hostname]; + : [hostname] - return subdomains.slice(offset); -}); + return subdomains.slice(offset) +}) /** * Short-hand for `url.parse(req.url).pathname`. @@ -387,9 +387,9 @@ defineGetter(req, 'subdomains', function subdomains() { * @public */ -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); +defineGetter(req, 'path', function path () { + return parse(this).pathname +}) /** * Parse the "Host" header field to a host. @@ -402,20 +402,20 @@ defineGetter(req, 'path', function path() { * @public */ -defineGetter(req, 'host', function host(){ - var trust = this.app.get('trust proxy fn'); - var val = this.get('X-Forwarded-Host'); +defineGetter(req, 'host', function host () { + const trust = this.app.get('trust proxy fn') + let val = this.get('X-Forwarded-Host') if (!val || !trust(this.socket.remoteAddress, 0)) { - val = this.get('Host'); + val = this.get('Host') } else if (val.indexOf(',') !== -1) { // Note: X-Forwarded-Host is normally only ever a // single value, but this is to be safe. val = val.substring(0, val.indexOf(',')).trimRight() } - return val || undefined; -}); + return val || undefined +}) /** * Parse the "Host" header field to a hostname. @@ -428,21 +428,21 @@ defineGetter(req, 'host', function host(){ * @api public */ -defineGetter(req, 'hostname', function hostname(){ - var host = this.host; +defineGetter(req, 'hostname', function hostname () { + const host = this.host - if (!host) return; + if (!host) return // IPv6 literal support - var offset = host[0] === '[' + const offset = host[0] === '[' ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); + : 0 + const index = host.indexOf(':', offset) return index !== -1 ? host.substring(0, index) - : host; -}); + : host +}) /** * Check if the request is fresh, aka @@ -453,24 +453,24 @@ defineGetter(req, 'hostname', function hostname(){ * @public */ -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode +defineGetter(req, 'fresh', function () { + const method = this.method + const res = this.res + const status = res.statusCode // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; + if (method !== 'GET' && method !== 'HEAD') return false // 2xx or 304 as per rfc2616 14.26 - if ((status >= 200 && status < 300) || 304 === status) { + if ((status >= 200 && status < 300) || status === 304) { return fresh(this.headers, { - 'etag': res.get('ETag'), + etag: res.get('ETag'), 'last-modified': res.get('Last-Modified') }) } - return false; -}); + return false +}) /** * Check if the request is stale, aka @@ -481,9 +481,9 @@ defineGetter(req, 'fresh', function(){ * @public */ -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); +defineGetter(req, 'stale', function stale () { + return !this.fresh +}) /** * Check if the request was an _XMLHttpRequest_. @@ -492,10 +492,10 @@ defineGetter(req, 'stale', function stale(){ * @public */ -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); +defineGetter(req, 'xhr', function xhr () { + const val = this.get('X-Requested-With') || '' + return val.toLowerCase() === 'xmlhttprequest' +}) /** * Helper function for creating a getter on an object. @@ -505,10 +505,10 @@ defineGetter(req, 'xhr', function xhr(){ * @param {Function} getter * @private */ -function defineGetter(obj, name, getter) { +function defineGetter (obj, name, getter) { Object.defineProperty(obj, name, { configurable: true, enumerable: true, get: getter - }); + }) } diff --git a/lib/response.js b/lib/response.js index 7a2f0ecce56..74d9c58c935 100644 --- a/lib/response.js +++ b/lib/response.js @@ -5,41 +5,39 @@ * MIT Licensed */ -'use strict'; +'use strict' /** * Module dependencies. * @private */ -var contentDisposition = require('content-disposition'); -var createError = require('http-errors') -var deprecate = require('depd')('express'); -var encodeUrl = require('encodeurl'); -var escapeHtml = require('escape-html'); -var http = require('node:http'); -var onFinished = require('on-finished'); -var mime = require('mime-types') -var path = require('node:path'); -var pathIsAbsolute = require('node:path').isAbsolute; -var statuses = require('statuses') -var sign = require('cookie-signature').sign; -var normalizeType = require('./utils').normalizeType; -var normalizeTypes = require('./utils').normalizeTypes; -var setCharset = require('./utils').setCharset; -var cookie = require('cookie'); -var send = require('send'); -var extname = path.extname; -var resolve = path.resolve; -var vary = require('vary'); -const { Buffer } = require('node:buffer'); +const contentDisposition = require('content-disposition') +const createError = require('http-errors') +const deprecate = require('depd')('express') +const encodeUrl = require('encodeurl') +const escapeHtml = require('escape-html') +const http = require('node:http') +const onFinished = require('on-finished') +const mime = require('mime-types') +const path = require('node:path') +const pathIsAbsolute = path.isAbsolute +const statuses = require('statuses') +const { sign } = require('cookie-signature') +const { normalizeType, normalizeTypes, setCharset } = require('./utils') +const cookie = require('cookie') +const send = require('send') +const extname = path.extname +const resolve = path.resolve +const vary = require('vary') +const { Buffer } = require('node:buffer') /** * Response prototype. * @public */ -var res = Object.create(http.ServerResponse.prototype) +const res = Object.create(http.ServerResponse.prototype) /** * Module exports. @@ -61,19 +59,19 @@ module.exports = res * @public */ -res.status = function status(code) { +res.status = function status (code) { // Check if the status code is not an integer if (!Number.isInteger(code)) { - throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`); + throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`) } // Check if the status code is outside of Node's valid range if (code < 100 || code > 999) { - throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`); + throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`) } - this.statusCode = code; - return this; -}; + this.statusCode = code + return this +} /** * Set Link header field with the given `links`. @@ -94,20 +92,20 @@ res.status = function status(code) { * @public */ -res.links = function(links) { - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel) { +res.links = function (links) { + let link = this.get('Link') || '' + if (link) link += ', ' + return this.set('Link', link + Object.keys(links).map((rel) => { // Allow multiple links if links[rel] is an array if (Array.isArray(links[rel])) { - return links[rel].map(function (singleLink) { - return `<${singleLink}>; rel="${rel}"`; - }).join(', '); + return links[rel].map((singleLink) => { + return `<${singleLink}>; rel="${rel}"` + }).join(', ') } else { - return `<${links[rel]}>; rel="${rel}"`; + return `<${links[rel]}>; rel="${rel}"` } - }).join(', ')); -}; + }).join(', ')) +} /** * Send a response. @@ -122,54 +120,54 @@ res.links = function(links) { * @public */ -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; +res.send = function send (body) { + let chunk = body + let encoding + const req = this.req + let type // settings - var app = this.app; + const app = this.app switch (typeof chunk) { // string defaulting to html case 'string': if (!this.get('Content-Type')) { - this.type('html'); + this.type('html') } - break; + break case 'boolean': case 'number': case 'object': if (chunk === null) { - chunk = ''; + chunk = '' } else if (ArrayBuffer.isView(chunk)) { if (!this.get('Content-Type')) { - this.type('bin'); + this.type('bin') } } else { - return this.json(chunk); + return this.json(chunk) } - break; + break } // write strings in utf-8 if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); + encoding = 'utf8' + type = this.get('Content-Type') // reflect this in content-type if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); + this.set('Content-Type', setCharset(type, 'utf-8')) } } // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' + const etagFn = app.get('etag fn') + const generateETag = !this.get('ETag') && typeof etagFn === 'function' // populate Content-Length - var len + let len if (chunk !== undefined) { if (Buffer.isBuffer(chunk)) { // get length of Buffer @@ -180,30 +178,30 @@ res.send = function send(body) { } else { // convert chunk to Buffer and calculate chunk = Buffer.from(chunk, encoding) - encoding = undefined; + encoding = undefined len = chunk.length } - this.set('Content-Length', len); + this.set('Content-Length', len) } // populate ETag - var etag; + let etag if (generateETag && len !== undefined) { if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); + this.set('ETag', etag) } } // freshness - if (req.fresh) this.status(304); + if (req.fresh) this.status(304) // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; + if (this.statusCode === 204 || this.statusCode === 304) { + this.removeHeader('Content-Type') + this.removeHeader('Content-Length') + this.removeHeader('Transfer-Encoding') + chunk = '' } // alter headers for 205 @@ -215,14 +213,14 @@ res.send = function send(body) { if (req.method === 'HEAD') { // skip body for HEAD - this.end(); + this.end() } else { // respond - this.end(chunk, encoding); + this.end(chunk, encoding) } - return this; -}; + return this +} /** * Send JSON response. @@ -236,21 +234,21 @@ res.send = function send(body) { * @public */ -res.json = function json(obj) { +res.json = function json (obj) { // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(obj, replacer, spaces, escape) + const app = this.app + const escape = app.get('json escape') + const replacer = app.get('json replacer') + const spaces = app.get('json spaces') + const body = stringify(obj, replacer, spaces, escape) // content-type if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); + this.set('Content-Type', 'application/json') } - return this.send(body); -}; + return this.send(body) +} /** * Send JSON response with JSONP callback support. @@ -264,33 +262,33 @@ res.json = function json(obj) { * @public */ -res.jsonp = function jsonp(obj) { +res.jsonp = function jsonp (obj) { // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(obj, replacer, spaces, escape) - var callback = this.req.query[app.get('jsonp callback name')]; + const app = this.app + const escape = app.get('json escape') + const replacer = app.get('json replacer') + const spaces = app.get('json spaces') + let body = stringify(obj, replacer, spaces, escape) + let callback = this.req.query[app.get('jsonp callback name')] // content-type if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); + this.set('X-Content-Type-Options', 'nosniff') + this.set('Content-Type', 'application/json') } // fixup callback if (Array.isArray(callback)) { - callback = callback[0]; + callback = callback[0] } // jsonp if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); + this.set('X-Content-Type-Options', 'nosniff') + this.set('Content-Type', 'text/javascript') // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); + callback = callback.replace(/[^[\]\w$.]/g, '') if (body === undefined) { // empty argument @@ -304,11 +302,11 @@ res.jsonp = function jsonp(obj) { // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');' } - return this.send(body); -}; + return this.send(body) +} /** * Send given HTTP status code. @@ -325,14 +323,14 @@ res.jsonp = function jsonp(obj) { * @public */ -res.sendStatus = function sendStatus(statusCode) { - var body = statuses.message[statusCode] || String(statusCode) +res.sendStatus = function sendStatus (statusCode) { + const body = statuses.message[statusCode] || String(statusCode) - this.status(statusCode); - this.type('txt'); + this.status(statusCode) + this.type('txt') - return this.send(body); -}; + return this.send(body) +} /** * Transfer the file at the given `path`. @@ -375,15 +373,15 @@ res.sendStatus = function sendStatus(statusCode) { * @public */ -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; +res.sendFile = function sendFile (path, options, callback) { + let done = callback + const req = this.req + const res = this + const next = req.next + let opts = options || {} if (!path) { - throw new TypeError('path argument is required to res.sendFile'); + throw new TypeError('path argument is required to res.sendFile') } if (typeof path !== 'string') { @@ -392,32 +390,32 @@ res.sendFile = function sendFile(path, options, callback) { // support function as second arg if (typeof options === 'function') { - done = options; - opts = {}; + done = options + opts = {} } if (!opts.root && !pathIsAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); + throw new TypeError('path must be absolute or specify root to res.sendFile') } // create file stream - var pathname = encodeURI(path); + const pathname = encodeURI(path) // wire application etag option to send - opts.etag = this.app.enabled('etag'); - var file = send(req, pathname, opts); + opts.etag = this.app.enabled('etag') + const file = send(req, pathname, opts) // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + sendfile(res, file, opts, (err) => { + if (done) return done(err) + if (err && err.code === 'EISDIR') return next() // next() all but write errors if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); + next(err) } - }); -}; + }) +} /** * Transfer the file at the given `path` as an attachment. @@ -438,14 +436,14 @@ res.sendFile = function sendFile(path, options, callback) { */ res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null + let done = callback + let name = filename + let opts = options || null // support function as second or third arg if (typeof filename === 'function') { - done = filename; - name = null; + done = filename + name = null opts = null } else if (typeof options === 'function') { done = options @@ -460,15 +458,15 @@ res.download = function download (path, filename, options, callback) { } // set Content-Disposition when file is sent - var headers = { + const headers = { 'Content-Disposition': contentDisposition(name || path) - }; + } // merge user-provided headers if (opts && opts.headers) { - var keys = Object.keys(opts.headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] + const keys = Object.keys(opts.headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] if (key.toLowerCase() !== 'content-disposition') { headers[key] = opts.headers[key] } @@ -480,13 +478,13 @@ res.download = function download (path, filename, options, callback) { opts.headers = headers // Resolve the full path for sendFile - var fullPath = !opts.root + const fullPath = !opts.root ? resolve(path) : path // send file return this.sendFile(fullPath, opts, done) -}; +} /** * Set _Content-Type_ response header with `type` through `mime.contentType()` @@ -508,13 +506,13 @@ res.download = function download (path, filename, options, callback) { */ res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 +res.type = function contentType (type) { + const ct = type.indexOf('/') === -1 ? (mime.contentType(type) || 'application/octet-stream') - : type; + : type - return this.set('Content-Type', ct); -}; + return this.set('Content-Type', ct) +} /** * Respond to the Acceptable formats using an `obj` @@ -573,32 +571,32 @@ res.type = function contentType(type) { * @public */ -res.format = function(obj){ - var req = this.req; - var next = req.next; +res.format = function (obj) { + const req = this.req + const next = req.next - var keys = Object.keys(obj) - .filter(function (v) { return v !== 'default' }) + const keys = Object.keys(obj) + .filter((v) => { return v !== 'default' }) - var key = keys.length > 0 + const key = keys.length > 0 ? req.accepts(keys) - : false; + : false - this.vary("Accept"); + this.vary('Accept') if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); + this.set('Content-Type', normalizeType(key).value) + obj[key](req, this, next) } else if (obj.default) { obj.default(req, this, next) } else { next(createError(406, { - types: normalizeTypes(keys).map(function (o) { return o.value }) + types: normalizeTypes(keys).map((o) => { return o.value }) })) } - return this; -}; + return this +} /** * Set _Content-Disposition_ header to _attachment_ with optional `filename`. @@ -608,15 +606,15 @@ res.format = function(obj){ * @public */ -res.attachment = function attachment(filename) { +res.attachment = function attachment (filename) { if (filename) { - this.type(extname(filename)); + this.type(extname(filename)) } - this.set('Content-Disposition', contentDisposition(filename)); + this.set('Content-Disposition', contentDisposition(filename)) - return this; -}; + return this +} /** * Append additional header `field` with value `val`. @@ -633,19 +631,21 @@ res.attachment = function attachment(filename) { * @public */ -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; +res.append = function append (field, val) { + const prev = this.get(field) + let value = val if (prev) { // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) + value = Array.isArray(prev) + ? prev.concat(val) + : Array.isArray(val) + ? [prev].concat(val) : [prev, val] } - return this.set(field, value); -}; + return this.set(field, value) +} /** * Set header `field` to `val`, or pass @@ -669,28 +669,28 @@ res.append = function append(field, val) { */ res.set = -res.header = function header(field, val) { +res.header = function header (field, val) { if (arguments.length === 2) { - var value = Array.isArray(val) + let value = Array.isArray(val) ? val.map(String) - : String(val); + : String(val) // add charset to content-type if (field.toLowerCase() === 'content-type') { if (Array.isArray(value)) { - throw new TypeError('Content-Type cannot be set to an Array'); + throw new TypeError('Content-Type cannot be set to an Array') } value = mime.contentType(value) } - this.setHeader(field, value); + this.setHeader(field, value) } else { - for (var key in field) { - this.set(key, field[key]); + for (const key in field) { + this.set(key, field[key]) } } - return this; -}; + return this +} /** * Get value for header `field`. @@ -700,9 +700,9 @@ res.header = function header(field, val) { * @public */ -res.get = function(field){ - return this.getHeader(field); -}; +res.get = function (field) { + return this.getHeader(field) +} /** * Clear cookie `name`. @@ -713,14 +713,14 @@ res.get = function(field){ * @public */ -res.clearCookie = function clearCookie(name, options) { +res.clearCookie = function clearCookie (name, options) { // Force cookie expiration by setting expires to the past - const opts = { path: '/', ...options, expires: new Date(1)}; + const opts = { path: '/', ...options, expires: new Date(1) } // ensure maxAge is not passed delete opts.maxAge - return this.cookie(name, '', opts); -}; + return this.cookie(name, '', opts) +} /** * Set cookie `name` to `value`, with the given `options`. @@ -747,24 +747,24 @@ res.clearCookie = function clearCookie(name, options) { */ res.cookie = function (name, value, options) { - var opts = { ...options }; - var secret = this.req.secret; - var signed = opts.signed; + const opts = { ...options } + const secret = this.req.secret + const signed = opts.signed if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); + throw new Error('cookieParser("secret") required for signed cookies') } - var val = typeof value === 'object' + let val = typeof value === 'object' ? 'j:' + JSON.stringify(value) - : String(value); + : String(value) if (signed) { - val = 's:' + sign(val, secret); + val = 's:' + sign(val, secret) } if (opts.maxAge != null) { - var maxAge = opts.maxAge - 0 + const maxAge = opts.maxAge - 0 if (!isNaN(maxAge)) { opts.expires = new Date(Date.now() + maxAge) @@ -773,13 +773,13 @@ res.cookie = function (name, value, options) { } if (opts.path == null) { - opts.path = '/'; + opts.path = '/' } - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)) - return this; -}; + return this +} /** * Set the location header to `url`. @@ -798,9 +798,9 @@ res.cookie = function (name, value, options) { * @public */ -res.location = function location(url) { - return this.set('Location', encodeUrl(url)); -}; +res.location = function location (url) { + return this.set('Location', encodeUrl(url)) +} /** * Redirect to the given `url` with optional response `status` @@ -816,10 +816,10 @@ res.location = function location(url) { * @public */ -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; +res.redirect = function redirect (url) { + let address = url + let body + let status = 302 // allow status / url if (arguments.length === 2) { @@ -828,46 +828,46 @@ res.redirect = function redirect(url) { } if (!address) { - deprecate('Provide a url argument'); + deprecate('Provide a url argument') } if (typeof address !== 'string') { - deprecate('Url must be a string'); + deprecate('Url must be a string') } if (typeof status !== 'number') { - deprecate('Status must be a number'); + deprecate('Status must be a number') } // Set location header - address = this.location(address).get('Location'); + address = this.location(address).get('Location') // Support text/{plain,html} by default this.format({ - text: function(){ + text: function () { body = statuses.message[status] + '. Redirecting to ' + address }, - html: function(){ - var u = escapeHtml(address); + html: function () { + const u = escapeHtml(address) body = '

' + statuses.message[status] + '. Redirecting to ' + u + '

' }, - default: function(){ - body = ''; + default: function () { + body = '' } - }); + }) // Respond - this.status(status); - this.set('Content-Length', Buffer.byteLength(body)); + this.status(status) + this.set('Content-Length', Buffer.byteLength(body)) if (this.req.method === 'HEAD') { - this.end(); + this.end() } else { - this.end(body); + this.end(body) } -}; +} /** * Add `field` to Vary. If already present in the Vary set, then @@ -878,11 +878,11 @@ res.redirect = function redirect(url) { * @public */ -res.vary = function(field){ - vary(this, field); +res.vary = function (field) { + vary(this, field) - return this; -}; + return this +} /** * Render `view` with the given `options` and optional callback `fn`. @@ -897,121 +897,121 @@ res.vary = function(field){ * @public */ -res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self = this; +res.render = function render (view, options, callback) { + const app = this.req.app + let done = callback + let opts = options || {} + const req = this.req + const self = this // support callback function as second arg if (typeof options === 'function') { - done = options; - opts = {}; + done = options + opts = {} } // merge res.locals - opts._locals = self.locals; + opts._locals = self.locals // default callback to respond done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; + if (err) return req.next(err) + self.send(str) + } // render - app.render(view, opts, done); -}; + app.render(view, opts, done) +} // pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; +function sendfile (res, file, options, callback) { + let done = false + let streaming // request aborted - function onaborted() { - if (done) return; - done = true; + function onaborted () { + if (done) return + done = true - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); + const err = new Error('Request aborted') + err.code = 'ECONNABORTED' + callback(err) } // directory - function ondirectory() { - if (done) return; - done = true; + function ondirectory () { + if (done) return + done = true - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); + const err = new Error('EISDIR, read') + err.code = 'EISDIR' + callback(err) } // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); + function onerror (err) { + if (done) return + done = true + callback(err) } // ended - function onend() { - if (done) return; - done = true; - callback(); + function onend () { + if (done) return + done = true + callback() } // file - function onfile() { - streaming = false; + function onfile () { + streaming = false } // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; + function onfinish (err) { + if (err && err.code === 'ECONNRESET') return onaborted() + if (err) return onerror(err) + if (done) return - setImmediate(function () { + setImmediate(() => { if (streaming !== false && !done) { - onaborted(); - return; + onaborted() + return } - if (done) return; - done = true; - callback(); - }); + if (done) return + done = true + callback() + }) } // streaming - function onstream() { - streaming = true; + function onstream () { + streaming = true } - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); + file.on('directory', ondirectory) + file.on('end', onend) + file.on('error', onerror) + file.on('file', onfile) + file.on('stream', onstream) + onFinished(res, onfinish) if (options.headers) { // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); + file.on('headers', (res) => { + const obj = options.headers + const keys = Object.keys(obj) - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); + for (let i = 0; i < keys.length; i++) { + const k = keys[i] + res.setHeader(k, obj[k]) } - }); + }) } // pipe - file.pipe(res); + file.pipe(res) } /** @@ -1029,12 +1029,12 @@ function sendfile(res, file, options, callback) { function stringify (value, replacer, spaces, escape) { // v8 checks arguments.length for optimizing simple call // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces + let json = replacer || spaces ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); + : JSON.stringify(value) if (escape && typeof json === 'string') { - json = json.replace(/[<>&]/g, function (c) { + json = json.replace(/[<>&]/g, (c) => { switch (c.charCodeAt(0)) { case 0x3c: return '\\u003c' diff --git a/lib/utils.js b/lib/utils.js index 4f21e7ef1e3..0a60f7531db 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -5,28 +5,27 @@ * MIT Licensed */ -'use strict'; +'use strict' /** * Module dependencies. * @api private */ -var { METHODS } = require('node:http'); -var contentType = require('content-type'); -var etag = require('etag'); -var mime = require('mime-types') -var proxyaddr = require('proxy-addr'); -var qs = require('qs'); -var querystring = require('node:querystring'); -const { Buffer } = require('node:buffer'); - +const { METHODS } = require('node:http') +const contentType = require('content-type') +const etag = require('etag') +const mime = require('mime-types') +const proxyaddr = require('proxy-addr') +const qs = require('qs') +const querystring = require('node:querystring') +const { Buffer } = require('node:buffer') /** * A list of lowercased HTTP methods that are supported by Node.js. * @api private */ -exports.methods = METHODS.map((method) => method.toLowerCase()); +exports.methods = METHODS.map((method) => method.toLowerCase()) /** * Return strong ETag for `body`. @@ -58,11 +57,11 @@ exports.wetag = createETagGenerator({ weak: true }) * @api private */ -exports.normalizeType = function(type){ +exports.normalizeType = function (type) { return ~type.indexOf('/') ? acceptParams(type) : { value: (mime.lookup(type) || 'application/octet-stream'), params: {} } -}; +} /** * Normalize `types`, for example "html" becomes "text/html". @@ -72,10 +71,9 @@ exports.normalizeType = function(type){ * @api private */ -exports.normalizeTypes = function(types) { - return types.map(exports.normalizeType); -}; - +exports.normalizeTypes = function (types) { + return types.map(exports.normalizeType) +} /** * Parse accept params `str` returning an @@ -87,36 +85,36 @@ exports.normalizeTypes = function(types) { */ function acceptParams (str) { - var length = str.length; - var colonIndex = str.indexOf(';'); - var index = colonIndex === -1 ? length : colonIndex; - var ret = { value: str.slice(0, index).trim(), quality: 1, params: {} }; + const length = str.length + let colonIndex = str.indexOf(';') + let index = colonIndex === -1 ? length : colonIndex + const ret = { value: str.slice(0, index).trim(), quality: 1, params: {} } while (index < length) { - var splitIndex = str.indexOf('=', index); - if (splitIndex === -1) break; + const splitIndex = str.indexOf('=', index) + if (splitIndex === -1) break - var colonIndex = str.indexOf(';', index); - var endIndex = colonIndex === -1 ? length : colonIndex; + colonIndex = str.indexOf(';', index) + const endIndex = colonIndex === -1 ? length : colonIndex if (splitIndex > endIndex) { - index = str.lastIndexOf(';', splitIndex - 1) + 1; - continue; + index = str.lastIndexOf(';', splitIndex - 1) + 1 + continue } - var key = str.slice(index, splitIndex).trim(); - var value = str.slice(splitIndex + 1, endIndex).trim(); + const key = str.slice(index, splitIndex).trim() + const value = str.slice(splitIndex + 1, endIndex).trim() if (key === 'q') { - ret.quality = parseFloat(value); + ret.quality = parseFloat(value) } else { - ret.params[key] = value; + ret.params[key] = value } - index = endIndex + 1; + index = endIndex + 1 } - return ret; + return ret } /** @@ -127,28 +125,28 @@ function acceptParams (str) { * @api private */ -exports.compileETag = function(val) { - var fn; +exports.compileETag = function (val) { + let fn if (typeof val === 'function') { - return val; + return val } switch (val) { case true: case 'weak': - fn = exports.wetag; - break; + fn = exports.wetag + break case false: - break; + break case 'strong': - fn = exports.etag; - break; + fn = exports.etag + break default: - throw new TypeError('unknown value for etag function: ' + val); + throw new TypeError('unknown value for etag function: ' + val) } - return fn; + return fn } /** @@ -159,28 +157,28 @@ exports.compileETag = function(val) { * @api private */ -exports.compileQueryParser = function compileQueryParser(val) { - var fn; +exports.compileQueryParser = function compileQueryParser (val) { + let fn if (typeof val === 'function') { - return val; + return val } switch (val) { case true: case 'simple': - fn = querystring.parse; - break; + fn = querystring.parse + break case false: - break; + break case 'extended': - fn = parseExtendedQueryString; - break; + fn = parseExtendedQueryString + break default: - throw new TypeError('unknown value for query parser function: ' + val); + throw new TypeError('unknown value for query parser function: ' + val) } - return fn; + return fn } /** @@ -191,26 +189,26 @@ exports.compileQueryParser = function compileQueryParser(val) { * @api private */ -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; +exports.compileTrust = function (val) { + if (typeof val === 'function') return val if (val === true) { // Support plain true/false - return function(){ return true }; + return function () { return true } } if (typeof val === 'number') { // Support trusting hop count - return function(a, i){ return i < val }; + return function (a, i) { return i < val } } if (typeof val === 'string') { // Support comma-separated values val = val.split(',') - .map(function (v) { return v.trim() }) + .map((v) => v.trim()) } - return proxyaddr.compile(val || []); + return proxyaddr.compile(val || []) } /** @@ -222,20 +220,20 @@ exports.compileTrust = function(val) { * @api private */ -exports.setCharset = function setCharset(type, charset) { +exports.setCharset = function setCharset (type, charset) { if (!type || !charset) { - return type; + return type } // parse type - var parsed = contentType.parse(type); + const parsed = contentType.parse(type) // set charset - parsed.parameters.charset = charset; + parsed.parameters.charset = charset // format type - return contentType.format(parsed); -}; + return contentType.format(parsed) +} /** * Create an ETag generator function, generating ETags with @@ -248,7 +246,7 @@ exports.setCharset = function setCharset(type, charset) { function createETagGenerator (options) { return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) + const buf = !Buffer.isBuffer(body) ? Buffer.from(body, encoding) : body @@ -264,8 +262,8 @@ function createETagGenerator (options) { * @private */ -function parseExtendedQueryString(str) { +function parseExtendedQueryString (str) { return qs.parse(str, { allowPrototypes: true - }); + }) } diff --git a/lib/view.js b/lib/view.js index d66b4a2d89c..383da24fc7a 100644 --- a/lib/view.js +++ b/lib/view.js @@ -6,34 +6,34 @@ * MIT Licensed */ -'use strict'; +'use strict' /** * Module dependencies. * @private */ -var debug = require('debug')('express:view'); -var path = require('node:path'); -var fs = require('node:fs'); +const debug = require('debug')('express:view') +const path = require('node:path') +const fs = require('node:fs') /** * Module variables. * @private */ -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; +const dirname = path.dirname +const basename = path.basename +const extname = path.extname +const join = path.join +const resolve = path.resolve /** * Module exports. * @public */ -module.exports = View; +module.exports = View /** * Initialize a new `View` with the given `name`. @@ -49,36 +49,37 @@ module.exports = View; * @public */ -function View(name, options) { - var opts = options || {}; +function View (name, options) { + const opts = options || {} - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; + this.defaultEngine = opts.defaultEngine + this.ext = extname(name) + this.name = name + this.root = opts.root if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); + throw new Error('No default engine was specified and no extension was provided.') } - var fileName = name; + let fileName = name if (!this.ext) { // get extension from default engine name this.ext = this.defaultEngine[0] !== '.' ? '.' + this.defaultEngine - : this.defaultEngine; + : this.defaultEngine - fileName += this.ext; + fileName += this.ext } if (!opts.engines[this.ext]) { // load engine - var mod = this.ext.slice(1) + const mod = this.ext.slice(1) debug('require "%s"', mod) // default engine export - var fn = require(mod).__express + // eslint-disable-next-line global-require + const fn = require(mod).__express if (typeof fn !== 'function') { throw new Error('Module "' + mod + '" does not provide a view engine.') @@ -88,10 +89,10 @@ function View(name, options) { } // store loaded engine - this.engine = opts.engines[this.ext]; + this.engine = opts.engines[this.ext] // lookup path - this.path = this.lookup(fileName); + this.path = this.lookup(fileName) } /** @@ -101,26 +102,26 @@ function View(name, options) { * @private */ -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); +View.prototype.lookup = function lookup (name) { + let path + const roots = [].concat(this.root) - debug('lookup "%s"', name); + debug('lookup "%s"', name) - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; + for (let i = 0; i < roots.length && !path; i++) { + const root = roots[i] // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); + const loc = resolve(root, name) + const dir = dirname(loc) + const file = basename(loc) // resolve the file - path = this.resolve(dir, file); + path = this.resolve(dir, file) } - return path; -}; + return path +} /** * Render with the given options. @@ -130,33 +131,33 @@ View.prototype.lookup = function lookup(name) { * @private */ -View.prototype.render = function render(options, callback) { - var sync = true; +View.prototype.render = function render (options, callback) { + let sync = true - debug('render "%s"', this.path); + debug('render "%s"', this.path) // render, normalizing sync callbacks - this.engine(this.path, options, function onRender() { + this.engine(this.path, options, function onRender () { if (!sync) { - return callback.apply(this, arguments); + return callback.apply(this, arguments) } // copy arguments - var args = new Array(arguments.length); - var cntx = this; + const args = new Array(arguments.length) + const cntx = this - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i] } // force callback to be async - return process.nextTick(function renderTick() { - return callback.apply(cntx, args); - }); - }); + return process.nextTick(function renderTick () { + return callback.apply(cntx, args) + }) + }) - sync = false; -}; + sync = false +} /** * Resolve the file within the given directory. @@ -166,25 +167,25 @@ View.prototype.render = function render(options, callback) { * @private */ -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; +View.prototype.resolve = function resolve (dir, file) { + const ext = this.ext // . - var path = join(dir, file); - var stat = tryStat(path); + let path = join(dir, file) + let stat = tryStat(path) if (stat && stat.isFile()) { - return path; + return path } // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); + path = join(dir, basename(file, ext), 'index' + ext) + stat = tryStat(path) if (stat && stat.isFile()) { - return path; + return path } -}; +} /** * Return a stat, maybe. @@ -194,12 +195,12 @@ View.prototype.resolve = function resolve(dir, file) { * @private */ -function tryStat(path) { - debug('stat "%s"', path); +function tryStat (path) { + debug('stat "%s"', path) try { - return fs.statSync(path); + return fs.statSync(path) } catch (e) { - return undefined; + return undefined } } diff --git a/package.json b/package.json index db7661de46d..6b730126508 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", + "neostandard": "^0.12.2", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", @@ -67,7 +68,7 @@ "cookie-parser": "1.4.7", "cookie-session": "2.1.1", "ejs": "^3.1.10", - "eslint": "8.47.0", + "eslint": "9.39.1", "express-session": "^1.18.1", "hbs": "4.2.0", "marked": "^15.0.3", diff --git a/test/Route.js b/test/Route.js index e4b73c7e6ec..d3b137314c4 100644 --- a/test/Route.js +++ b/test/Route.js @@ -1,42 +1,41 @@ 'use strict' -var after = require('after'); -var assert = require('node:assert') -var express = require('../') - , Route = express.Route - , methods = require('../lib/utils').methods - -describe('Route', function(){ - it('should work without handlers', function(done) { - var req = { method: 'GET', url: '/' } - var route = new Route('/foo') +const after = require('after') +const assert = require('node:assert') +const { Route } = require('../') +const { methods } = require('../lib/utils') + +describe('Route', () => { + it('should work without handlers', (done) => { + const req = { method: 'GET', url: '/' } + const route = new Route('/foo') route.dispatch(req, {}, done) }) it('should not stack overflow with a large sync stack', function (done) { this.timeout(5000) // long-running test - var req = { method: 'GET', url: '/' } - var route = new Route('/foo') + const req = { method: 'GET', url: '/' } + const route = new Route('/foo') - route.get(function (req, res, next) { + route.get((req, res, next) => { req.counter = 0 next() }) - for (var i = 0; i < 6000; i++) { - route.all(function (req, res, next) { + for (let i = 0; i < 6000; i++) { + route.all((req, res, next) => { req.counter++ next() }) } - route.get(function (req, res, next) { + route.get((req, res, next) => { req.called = true next() }) - route.dispatch(req, {}, function (err) { + route.dispatch(req, {}, (err) => { if (err) return done(err) assert.ok(req.called) assert.strictEqual(req.counter, 6000) @@ -44,231 +43,231 @@ describe('Route', function(){ }) }) - describe('.all', function(){ - it('should add handler', function(done){ - var req = { method: 'GET', url: '/' }; - var route = new Route('/foo'); + describe('.all', () => { + it('should add handler', (done) => { + const req = { method: 'GET', url: '/' } + const route = new Route('/foo') - route.all(function(req, res, next) { - req.called = true; - next(); - }); + route.all((req, res, next) => { + req.called = true + next() + }) - route.dispatch(req, {}, function (err) { - if (err) return done(err); + route.dispatch(req, {}, (err) => { + if (err) return done(err) assert.ok(req.called) - done(); - }); + done() + }) }) - it('should handle VERBS', function(done) { - var count = 0; - var route = new Route('/foo'); - var cb = after(methods.length, function (err) { - if (err) return done(err); + it('should handle VERBS', (done) => { + let count = 0 + const route = new Route('/foo') + const cb = after(methods.length, (err) => { + if (err) return done(err) assert.strictEqual(count, methods.length) - done(); - }); - - route.all(function(req, res, next) { - count++; - next(); - }); - - methods.forEach(function testMethod(method) { - var req = { method: method, url: '/' }; - route.dispatch(req, {}, cb); - }); + done() + }) + + route.all((req, res, next) => { + count++ + next() + }) + + methods.forEach((method) => { + const req = { method, url: '/' } + route.dispatch(req, {}, cb) + }) }) - it('should stack', function(done) { - var req = { count: 0, method: 'GET', url: '/' }; - var route = new Route('/foo'); + it('should stack', (done) => { + const req = { count: 0, method: 'GET', url: '/' } + const route = new Route('/foo') - route.all(function(req, res, next) { - req.count++; - next(); - }); + route.all((req, res, next) => { + req.count++ + next() + }) - route.all(function(req, res, next) { - req.count++; - next(); - }); + route.all((req, res, next) => { + req.count++ + next() + }) - route.dispatch(req, {}, function (err) { - if (err) return done(err); + route.dispatch(req, {}, (err) => { + if (err) return done(err) assert.strictEqual(req.count, 2) - done(); - }); + done() + }) }) }) - describe('.VERB', function(){ - it('should support .get', function(done){ - var req = { method: 'GET', url: '/' }; - var route = new Route(''); + describe('.VERB', () => { + it('should support .get', (done) => { + const req = { method: 'GET', url: '/' } + const route = new Route('') - route.get(function(req, res, next) { - req.called = true; - next(); + route.get((req, res, next) => { + req.called = true + next() }) - route.dispatch(req, {}, function (err) { - if (err) return done(err); + route.dispatch(req, {}, (err) => { + if (err) return done(err) assert.ok(req.called) - done(); - }); + done() + }) }) - it('should limit to just .VERB', function(done){ - var req = { method: 'POST', url: '/' }; - var route = new Route(''); + it('should limit to just .VERB', (done) => { + const req = { method: 'POST', url: '/' } + const route = new Route('') - route.get(function () { - throw new Error('not me!'); + route.get(() => { + throw new Error('not me!') }) - route.post(function(req, res, next) { - req.called = true; - next(); + route.post((req, res, next) => { + req.called = true + next() }) - route.dispatch(req, {}, function (err) { - if (err) return done(err); + route.dispatch(req, {}, (err) => { + if (err) return done(err) assert.ok(req.called) - done(); - }); + done() + }) }) - it('should allow fallthrough', function(done){ - var req = { order: '', method: 'GET', url: '/' }; - var route = new Route(''); + it('should allow fallthrough', (done) => { + const req = { order: '', method: 'GET', url: '/' } + const route = new Route('') - route.get(function(req, res, next) { - req.order += 'a'; - next(); + route.get((req, res, next) => { + req.order += 'a' + next() }) - route.all(function(req, res, next) { - req.order += 'b'; - next(); - }); + route.all((req, res, next) => { + req.order += 'b' + next() + }) - route.get(function(req, res, next) { - req.order += 'c'; - next(); + route.get((req, res, next) => { + req.order += 'c' + next() }) - route.dispatch(req, {}, function (err) { - if (err) return done(err); + route.dispatch(req, {}, (err) => { + if (err) return done(err) assert.strictEqual(req.order, 'abc') - done(); - }); + done() + }) }) }) - describe('errors', function(){ - it('should handle errors via arity 4 functions', function(done){ - var req = { order: '', method: 'GET', url: '/' }; - var route = new Route(''); + describe('errors', () => { + it('should handle errors via arity 4 functions', (done) => { + const req = { order: '', method: 'GET', url: '/' } + const route = new Route('') - route.all(function(req, res, next){ - next(new Error('foobar')); - }); + route.all((req, res, next) => { + next(new Error('foobar')) + }) - route.all(function(req, res, next){ - req.order += '0'; - next(); - }); + route.all((req, res, next) => { + req.order += '0' + next() + }) - route.all(function(err, req, res, next){ - req.order += 'a'; - next(err); - }); + route.all((err, req, res, next) => { + req.order += 'a' + next(err) + }) - route.dispatch(req, {}, function (err) { + route.dispatch(req, {}, (err) => { assert.ok(err) assert.strictEqual(err.message, 'foobar') assert.strictEqual(req.order, 'a') - done(); - }); + done() + }) }) - it('should handle throw', function(done) { - var req = { order: '', method: 'GET', url: '/' }; - var route = new Route(''); + it('should handle throw', (done) => { + const req = { order: '', method: 'GET', url: '/' } + const route = new Route('') - route.all(function () { - throw new Error('foobar'); - }); + route.all(() => { + throw new Error('foobar') + }) - route.all(function(req, res, next){ - req.order += '0'; - next(); - }); + route.all((req, res, next) => { + req.order += '0' + next() + }) - route.all(function(err, req, res, next){ - req.order += 'a'; - next(err); - }); + route.all((err, req, res, next) => { + req.order += 'a' + next(err) + }) - route.dispatch(req, {}, function (err) { + route.dispatch(req, {}, (err) => { assert.ok(err) assert.strictEqual(err.message, 'foobar') assert.strictEqual(req.order, 'a') - done(); - }); - }); + done() + }) + }) - it('should handle throwing inside error handlers', function(done) { - var req = { method: 'GET', url: '/' }; - var route = new Route(''); + it('should handle throwing inside error handlers', (done) => { + const req = { method: 'GET', url: '/' } + const route = new Route('') - route.get(function () { - throw new Error('boom!'); - }); + route.get(() => { + throw new Error('boom!') + }) - route.get(function(err, req, res, next){ - throw new Error('oops'); - }); + route.get((err, req, res, next) => { + throw new Error('oops') + }) - route.get(function(err, req, res, next){ - req.message = err.message; - next(); - }); + route.get((err, req, res, next) => { + req.message = err.message + next() + }) - route.dispatch(req, {}, function (err) { - if (err) return done(err); + route.dispatch(req, {}, (err) => { + if (err) return done(err) assert.strictEqual(req.message, 'oops') - done(); - }); - }); + done() + }) + }) - it('should handle throw in .all', function(done) { - var req = { method: 'GET', url: '/' }; - var route = new Route(''); + it('should handle throw in .all', (done) => { + const req = { method: 'GET', url: '/' } + const route = new Route('') - route.all(function(req, res, next){ - throw new Error('boom!'); - }); + route.all((req, res, next) => { + throw new Error('boom!') + }) - route.dispatch(req, {}, function(err){ + route.dispatch(req, {}, (err) => { assert.ok(err) assert.strictEqual(err.message, 'boom!') - done(); - }); - }); + done() + }) + }) - it('should handle single error handler', function(done) { - var req = { method: 'GET', url: '/' }; - var route = new Route(''); + it('should handle single error handler', (done) => { + const req = { method: 'GET', url: '/' } + const route = new Route('') - route.all(function(err, req, res, next){ + route.all((err, req, res, next) => { // this should not execute throw new Error('should not be called') - }); + }) - route.dispatch(req, {}, done); - }); + route.dispatch(req, {}, done) + }) }) }) diff --git a/test/Router.js b/test/Router.js index 7bac7159b04..1e57925d9c6 100644 --- a/test/Router.js +++ b/test/Router.js @@ -1,86 +1,85 @@ 'use strict' -var after = require('after'); -var express = require('../') - , Router = express.Router - , methods = require('../lib/utils').methods - , assert = require('node:assert'); - -describe('Router', function () { - it('should return a function with router methods', function () { - var router = new Router(); +const after = require('after') +const { Router } = require('../') +const { methods } = require('../lib/utils') +const assert = require('node:assert') + +describe('Router', () => { + it('should return a function with router methods', () => { + const router = new Router() assert(typeof router === 'function') assert(typeof router.get === 'function') assert(typeof router.handle === 'function') assert(typeof router.use === 'function') - }); + }) - it('should support .use of other routers', function (done) { - var router = new Router(); - var another = new Router(); + it('should support .use of other routers', (done) => { + const router = new Router() + const another = new Router() - another.get('/bar', function (req, res) { - res.end(); - }); - router.use('/foo', another); + another.get('/bar', (req, res) => { + res.end() + }) + router.use('/foo', another) - router.handle({ url: '/foo/bar', method: 'GET' }, { end: done }, function () { }); - }); + router.handle({ url: '/foo/bar', method: 'GET' }, { end: done }, () => { }) + }) - it('should support dynamic routes', function (done) { - var router = new Router(); - var another = new Router(); + it('should support dynamic routes', (done) => { + const router = new Router() + const another = new Router() - another.get('/:bar', function (req, res) { + another.get('/:bar', (req, res) => { assert.strictEqual(req.params.bar, 'route') - res.end(); - }); - router.use('/:foo', another); + res.end() + }) + router.use('/:foo', another) - router.handle({ url: '/test/route', method: 'GET' }, { end: done }, function () { }); - }); + router.handle({ url: '/test/route', method: 'GET' }, { end: done }, () => { }) + }) - it('should handle blank URL', function (done) { - var router = new Router(); + it('should handle blank URL', (done) => { + const router = new Router() - router.use(function (req, res) { + router.use((req, res) => { throw new Error('should not be called') - }); + }) - router.handle({ url: '', method: 'GET' }, {}, done); - }); + router.handle({ url: '', method: 'GET' }, {}, done) + }) - it('should handle missing URL', function (done) { - var router = new Router() + it('should handle missing URL', (done) => { + const router = new Router() - router.use(function (req, res) { + router.use((req, res) => { throw new Error('should not be called') }) router.handle({ method: 'GET' }, {}, done) }) - it('handle missing method', function (done) { - var all = false - var router = new Router() - var route = router.route('/foo') - var use = false + it('handle missing method', (done) => { + let all = false + const router = new Router() + const route = router.route('/foo') + let use = false - route.post(function (req, res, next) { next(new Error('should not run')) }) - route.all(function (req, res, next) { + route.post((req, res, next) => { next(new Error('should not run')) }) + route.all((req, res, next) => { all = true next() }) - route.get(function (req, res, next) { next(new Error('should not run')) }) + route.get((req, res, next) => { next(new Error('should not run')) }) - router.get('/foo', function (req, res, next) { next(new Error('should not run')) }) - router.use(function (req, res, next) { + router.get('/foo', (req, res, next) => { next(new Error('should not run')) }) + router.use((req, res, next) => { use = true next() }) - router.handle({ url: '/foo' }, {}, function (err) { + router.handle({ url: '/foo' }, {}, (err) => { if (err) return done(err) assert.ok(all) assert.ok(use) @@ -91,380 +90,380 @@ describe('Router', function () { it('should not stack overflow with many registered routes', function (done) { this.timeout(5000) // long-running test - var handler = function (req, res) { res.end(new Error('wrong handler')) }; - var router = new Router(); + const handler = function (req, res) { res.end(new Error('wrong handler')) } + const router = new Router() - for (var i = 0; i < 6000; i++) { + for (let i = 0; i < 6000; i++) { router.get('/thing' + i, handler) } - router.get('/', function (req, res) { - res.end(); - }); + router.get('/', (req, res) => { + res.end() + }) - router.handle({ url: '/', method: 'GET' }, { end: done }, function () { }); - }); + router.handle({ url: '/', method: 'GET' }, { end: done }, () => { }) + }) it('should not stack overflow with a large sync route stack', function (done) { this.timeout(5000) // long-running test - var router = new Router() + const router = new Router() - router.get('/foo', function (req, res, next) { + router.get('/foo', (req, res, next) => { req.counter = 0 next() }) - for (var i = 0; i < 6000; i++) { - router.get('/foo', function (req, res, next) { + for (let i = 0; i < 6000; i++) { + router.get('/foo', (req, res, next) => { req.counter++ next() }) } - router.get('/foo', function (req, res) { + router.get('/foo', (req, res) => { assert.strictEqual(req.counter, 6000) res.end() }) - router.handle({ url: '/foo', method: 'GET' }, { end: done }, function (err) { - assert(!err, err); - }); + router.handle({ url: '/foo', method: 'GET' }, { end: done }, (err) => { + assert(!err, err) + }) }) it('should not stack overflow with a large sync middleware stack', function (done) { this.timeout(5000) // long-running test - var router = new Router() + const router = new Router() - router.use(function (req, res, next) { + router.use((req, res, next) => { req.counter = 0 next() }) - for (var i = 0; i < 6000; i++) { - router.use(function (req, res, next) { + for (let i = 0; i < 6000; i++) { + router.use((req, res, next) => { req.counter++ next() }) } - router.use(function (req, res) { + router.use((req, res) => { assert.strictEqual(req.counter, 6000) res.end() }) - router.handle({ url: '/', method: 'GET' }, { end: done }, function (err) { - assert(!err, err); + router.handle({ url: '/', method: 'GET' }, { end: done }, (err) => { + assert(!err, err) }) }) - describe('.handle', function () { - it('should dispatch', function (done) { - var router = new Router(); + describe('.handle', () => { + it('should dispatch', (done) => { + const router = new Router() - router.route('/foo').get(function (req, res) { - res.send('foo'); - }); + router.route('/foo').get((req, res) => { + res.send('foo') + }) - var res = { + const res = { send: function (val) { assert.strictEqual(val, 'foo') - done(); + done() } } - router.handle({ url: '/foo', method: 'GET' }, res, function () { }); + router.handle({ url: '/foo', method: 'GET' }, res, () => { }) }) }) - describe('.multiple callbacks', function () { - it('should throw if a callback is null', function () { - assert.throws(function () { - var router = new Router(); - router.route('/foo').all(null); + describe('.multiple callbacks', () => { + it('should throw if a callback is null', () => { + assert.throws(() => { + const router = new Router() + router.route('/foo').all(null) }) }) - it('should throw if a callback is undefined', function () { - assert.throws(function () { - var router = new Router(); - router.route('/foo').all(undefined); + it('should throw if a callback is undefined', () => { + assert.throws(() => { + const router = new Router() + router.route('/foo').all(undefined) }) }) - it('should throw if a callback is not a function', function () { - assert.throws(function () { - var router = new Router(); - router.route('/foo').all('not a function'); + it('should throw if a callback is not a function', () => { + assert.throws(() => { + const router = new Router() + router.route('/foo').all('not a function') }) }) - it('should not throw if all callbacks are functions', function () { - var router = new Router(); - router.route('/foo').all(function () { }).all(function () { }); + it('should not throw if all callbacks are functions', () => { + const router = new Router() + router.route('/foo').all(() => { }).all(() => { }) }) }) - describe('error', function () { - it('should skip non error middleware', function (done) { - var router = new Router(); + describe('error', () => { + it('should skip non error middleware', (done) => { + const router = new Router() - router.get('/foo', function (req, res, next) { - next(new Error('foo')); - }); + router.get('/foo', (req, res, next) => { + next(new Error('foo')) + }) - router.get('/bar', function (req, res, next) { - next(new Error('bar')); - }); + router.get('/bar', (req, res, next) => { + next(new Error('bar')) + }) - router.use(function (req, res, next) { - assert(false); - }); + router.use((req, res, next) => { + assert(false) + }) - router.use(function (err, req, res, next) { - assert.equal(err.message, 'foo'); - done(); - }); + router.use((err, req, res, next) => { + assert.equal(err.message, 'foo') + done() + }) - router.handle({ url: '/foo', method: 'GET' }, {}, done); - }); + router.handle({ url: '/foo', method: 'GET' }, {}, done) + }) - it('should handle throwing inside routes with params', function (done) { - var router = new Router(); + it('should handle throwing inside routes with params', (done) => { + const router = new Router() - router.get('/foo/:id', function () { - throw new Error('foo'); - }); + router.get('/foo/:id', () => { + throw new Error('foo') + }) - router.use(function (req, res, next) { - assert(false); - }); + router.use((req, res, next) => { + assert(false) + }) - router.use(function (err, req, res, next) { - assert.equal(err.message, 'foo'); - done(); - }); + router.use((err, req, res, next) => { + assert.equal(err.message, 'foo') + done() + }) - router.handle({ url: '/foo/2', method: 'GET' }, {}, function () { }); - }); + router.handle({ url: '/foo/2', method: 'GET' }, {}, () => { }) + }) - it('should handle throwing in handler after async param', function (done) { - var router = new Router(); + it('should handle throwing in handler after async param', (done) => { + const router = new Router() - router.param('user', function (req, res, next, val) { - process.nextTick(function () { - req.user = val; - next(); - }); - }); + router.param('user', (req, res, next, val) => { + process.nextTick(() => { + req.user = val + next() + }) + }) - router.use('/:user', function (req, res, next) { - throw new Error('oh no!'); - }); + router.use('/:user', (req, res, next) => { + throw new Error('oh no!') + }) - router.use(function (err, req, res, next) { - assert.equal(err.message, 'oh no!'); - done(); - }); + router.use((err, req, res, next) => { + assert.equal(err.message, 'oh no!') + done() + }) - router.handle({ url: '/bob', method: 'GET' }, {}, function () { }); - }); + router.handle({ url: '/bob', method: 'GET' }, {}, () => { }) + }) - it('should handle throwing inside error handlers', function (done) { - var router = new Router(); + it('should handle throwing inside error handlers', (done) => { + const router = new Router() - router.use(function (req, res, next) { - throw new Error('boom!'); - }); + router.use((req, res, next) => { + throw new Error('boom!') + }) - router.use(function (err, req, res, next) { - throw new Error('oops'); - }); + router.use((err, req, res, next) => { + throw new Error('oops') + }) - router.use(function (err, req, res, next) { - assert.equal(err.message, 'oops'); - done(); - }); + router.use((err, req, res, next) => { + assert.equal(err.message, 'oops') + done() + }) - router.handle({ url: '/', method: 'GET' }, {}, done); - }); + router.handle({ url: '/', method: 'GET' }, {}, done) + }) }) - describe('FQDN', function () { - it('should not obscure FQDNs', function (done) { - var request = { hit: 0, url: 'http://example.com/foo', method: 'GET' }; - var router = new Router(); - - router.use(function (req, res, next) { - assert.equal(req.hit++, 0); - assert.equal(req.url, 'http://example.com/foo'); - next(); - }); - - router.handle(request, {}, function (err) { - if (err) return done(err); - assert.equal(request.hit, 1); - done(); - }); - }); - - it('should ignore FQDN in search', function (done) { - var request = { hit: 0, url: '/proxy?url=http://example.com/blog/post/1', method: 'GET' }; - var router = new Router(); - - router.use('/proxy', function (req, res, next) { - assert.equal(req.hit++, 0); - assert.equal(req.url, '/?url=http://example.com/blog/post/1'); - next(); - }); - - router.handle(request, {}, function (err) { - if (err) return done(err); - assert.equal(request.hit, 1); - done(); - }); - }); - - it('should ignore FQDN in path', function (done) { - var request = { hit: 0, url: '/proxy/http://example.com/blog/post/1', method: 'GET' }; - var router = new Router(); - - router.use('/proxy', function (req, res, next) { - assert.equal(req.hit++, 0); - assert.equal(req.url, '/http://example.com/blog/post/1'); - next(); - }); - - router.handle(request, {}, function (err) { - if (err) return done(err); - assert.equal(request.hit, 1); - done(); - }); - }); - - it('should adjust FQDN req.url', function (done) { - var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' }; - var router = new Router(); - - router.use('/blog', function (req, res, next) { - assert.equal(req.hit++, 0); - assert.equal(req.url, 'http://example.com/post/1'); - next(); - }); - - router.handle(request, {}, function (err) { - if (err) return done(err); - assert.equal(request.hit, 1); - done(); - }); - }); - - it('should adjust FQDN req.url with multiple handlers', function (done) { - var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' }; - var router = new Router(); - - router.use(function (req, res, next) { - assert.equal(req.hit++, 0); - assert.equal(req.url, 'http://example.com/blog/post/1'); - next(); - }); - - router.use('/blog', function (req, res, next) { - assert.equal(req.hit++, 1); - assert.equal(req.url, 'http://example.com/post/1'); - next(); - }); - - router.handle(request, {}, function (err) { - if (err) return done(err); - assert.equal(request.hit, 2); - done(); - }); - }); - - it('should adjust FQDN req.url with multiple routed handlers', function (done) { - var request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' }; - var router = new Router(); - - router.use('/blog', function (req, res, next) { - assert.equal(req.hit++, 0); - assert.equal(req.url, 'http://example.com/post/1'); - next(); - }); - - router.use('/blog', function (req, res, next) { - assert.equal(req.hit++, 1); - assert.equal(req.url, 'http://example.com/post/1'); - next(); - }); - - router.use(function (req, res, next) { - assert.equal(req.hit++, 2); - assert.equal(req.url, 'http://example.com/blog/post/1'); - next(); - }); - - router.handle(request, {}, function (err) { - if (err) return done(err); - assert.equal(request.hit, 3); - done(); - }); - }); + describe('FQDN', () => { + it('should not obscure FQDNs', (done) => { + const request = { hit: 0, url: 'http://example.com/foo', method: 'GET' } + const router = new Router() + + router.use((req, res, next) => { + assert.equal(req.hit++, 0) + assert.equal(req.url, 'http://example.com/foo') + next() + }) + + router.handle(request, {}, (err) => { + if (err) return done(err) + assert.equal(request.hit, 1) + done() + }) + }) + + it('should ignore FQDN in search', (done) => { + const request = { hit: 0, url: '/proxy?url=http://example.com/blog/post/1', method: 'GET' } + const router = new Router() + + router.use('/proxy', (req, res, next) => { + assert.equal(req.hit++, 0) + assert.equal(req.url, '/?url=http://example.com/blog/post/1') + next() + }) + + router.handle(request, {}, (err) => { + if (err) return done(err) + assert.equal(request.hit, 1) + done() + }) + }) + + it('should ignore FQDN in path', (done) => { + const request = { hit: 0, url: '/proxy/http://example.com/blog/post/1', method: 'GET' } + const router = new Router() + + router.use('/proxy', (req, res, next) => { + assert.equal(req.hit++, 0) + assert.equal(req.url, '/http://example.com/blog/post/1') + next() + }) + + router.handle(request, {}, (err) => { + if (err) return done(err) + assert.equal(request.hit, 1) + done() + }) + }) + + it('should adjust FQDN req.url', (done) => { + const request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' } + const router = new Router() + + router.use('/blog', (req, res, next) => { + assert.equal(req.hit++, 0) + assert.equal(req.url, 'http://example.com/post/1') + next() + }) + + router.handle(request, {}, (err) => { + if (err) return done(err) + assert.equal(request.hit, 1) + done() + }) + }) + + it('should adjust FQDN req.url with multiple handlers', (done) => { + const request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' } + const router = new Router() + + router.use((req, res, next) => { + assert.equal(req.hit++, 0) + assert.equal(req.url, 'http://example.com/blog/post/1') + next() + }) + + router.use('/blog', (req, res, next) => { + assert.equal(req.hit++, 1) + assert.equal(req.url, 'http://example.com/post/1') + next() + }) + + router.handle(request, {}, (err) => { + if (err) return done(err) + assert.equal(request.hit, 2) + done() + }) + }) + + it('should adjust FQDN req.url with multiple routed handlers', (done) => { + const request = { hit: 0, url: 'http://example.com/blog/post/1', method: 'GET' } + const router = new Router() + + router.use('/blog', (req, res, next) => { + assert.equal(req.hit++, 0) + assert.equal(req.url, 'http://example.com/post/1') + next() + }) + + router.use('/blog', (req, res, next) => { + assert.equal(req.hit++, 1) + assert.equal(req.url, 'http://example.com/post/1') + next() + }) + + router.use((req, res, next) => { + assert.equal(req.hit++, 2) + assert.equal(req.url, 'http://example.com/blog/post/1') + next() + }) + + router.handle(request, {}, (err) => { + if (err) return done(err) + assert.equal(request.hit, 3) + done() + }) + }) }) - describe('.all', function () { - it('should support using .all to capture all http verbs', function (done) { - var router = new Router(); + describe('.all', () => { + it('should support using .all to capture all http verbs', (done) => { + const router = new Router() - var count = 0; - router.all('/foo', function () { count++; }); + let count = 0 + router.all('/foo', () => { count++ }) - var url = '/foo?bar=baz'; + const url = '/foo?bar=baz' - methods.forEach(function testMethod(method) { - router.handle({ url: url, method: method }, {}, function () { }); - }); + methods.forEach((method) => { + router.handle({ url, method }, {}, () => { }) + }) - assert.equal(count, methods.length); - done(); + assert.equal(count, methods.length) + done() }) }) - describe('.use', function () { - it('should require middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/') }, /argument handler is required/) + describe('.use', () => { + it('should require middleware', () => { + const router = new Router() + assert.throws(() => { router.use('/') }, /argument handler is required/) }) - it('should reject string as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', 'foo') }, /argument handler must be a function/) + it('should reject string as middleware', () => { + const router = new Router() + assert.throws(() => { router.use('/', 'foo') }, /argument handler must be a function/) }) - it('should reject number as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', 42) }, /argument handler must be a function/) + it('should reject number as middleware', () => { + const router = new Router() + assert.throws(() => { router.use('/', 42) }, /argument handler must be a function/) }) - it('should reject null as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', null) }, /argument handler must be a function/) + it('should reject null as middleware', () => { + const router = new Router() + assert.throws(() => { router.use('/', null) }, /argument handler must be a function/) }) - it('should reject Date as middleware', function () { - var router = new Router() - assert.throws(function () { router.use('/', new Date()) }, /argument handler must be a function/) + it('should reject Date as middleware', () => { + const router = new Router() + assert.throws(() => { router.use('/', new Date()) }, /argument handler must be a function/) }) - it('should be called for any URL', function (done) { - var cb = after(4, done) - var router = new Router() + it('should be called for any URL', (done) => { + const cb = after(4, done) + const router = new Router() - function no() { + function no () { throw new Error('should not be called') } - router.use(function (req, res) { + router.use((req, res) => { res.end() }) @@ -474,163 +473,162 @@ describe('Router', function () { router.handle({ url: '*', method: 'GET' }, { end: cb }, no) }) - it('should accept array of middleware', function (done) { - var count = 0; - var router = new Router(); + it('should accept array of middleware', (done) => { + let count = 0 + const router = new Router() - function fn1(req, res, next) { - assert.equal(++count, 1); - next(); + function fn1 (req, res, next) { + assert.equal(++count, 1) + next() } - function fn2(req, res, next) { - assert.equal(++count, 2); - next(); + function fn2 (req, res, next) { + assert.equal(++count, 2) + next() } - router.use([fn1, fn2], function (req, res) { - assert.equal(++count, 3); - done(); - }); + router.use([fn1, fn2], (req, res) => { + assert.equal(++count, 3) + done() + }) - router.handle({ url: '/foo', method: 'GET' }, {}, function () { }); + router.handle({ url: '/foo', method: 'GET' }, {}, () => { }) }) }) - describe('.param', function () { - it('should require function', function () { - var router = new Router(); - assert.throws(router.param.bind(router, 'id'), /argument fn is required/); - }); - - it('should reject non-function', function () { - var router = new Router(); - assert.throws(router.param.bind(router, 'id', 42), /argument fn must be a function/); - }); - - it('should call param function when routing VERBS', function (done) { - var router = new Router(); - - router.param('id', function (req, res, next, id) { - assert.equal(id, '123'); - next(); - }); - - router.get('/foo/:id/bar', function (req, res, next) { - assert.equal(req.params.id, '123'); - next(); - }); - - router.handle({ url: '/foo/123/bar', method: 'get' }, {}, done); - }); - - it('should call param function when routing middleware', function (done) { - var router = new Router(); - - router.param('id', function (req, res, next, id) { - assert.equal(id, '123'); - next(); - }); - - router.use('/foo/:id/bar', function (req, res, next) { - assert.equal(req.params.id, '123'); - assert.equal(req.url, '/baz'); - next(); - }); - - router.handle({ url: '/foo/123/bar/baz', method: 'get' }, {}, done); - }); - - it('should only call once per request', function (done) { - var count = 0; - var req = { url: '/foo/bob/bar', method: 'get' }; - var router = new Router(); - var sub = new Router(); - - sub.get('/bar', function (req, res, next) { - next(); - }); - - router.param('user', function (req, res, next, user) { - count++; - req.user = user; - next(); - }); - - router.use('/foo/:user/', new Router()); - router.use('/foo/:user/', sub); - - router.handle(req, {}, function (err) { - if (err) return done(err); - assert.equal(count, 1); - assert.equal(req.user, 'bob'); - done(); - }); - }); - - it('should call when values differ', function (done) { - var count = 0; - var req = { url: '/foo/bob/bar', method: 'get' }; - var router = new Router(); - var sub = new Router(); - - sub.get('/bar', function (req, res, next) { - next(); - }); - - router.param('user', function (req, res, next, user) { - count++; - req.user = user; - next(); - }); - - router.use('/foo/:user/', new Router()); - router.use('/:user/bob/', sub); - - router.handle(req, {}, function (err) { - if (err) return done(err); - assert.equal(count, 2); - assert.equal(req.user, 'foo'); - done(); - }); - }); - }); - - describe('parallel requests', function () { - it('should not mix requests', function (done) { - var req1 = { url: '/foo/50/bar', method: 'get' }; - var req2 = { url: '/foo/10/bar', method: 'get' }; - var router = new Router(); - var sub = new Router(); - var cb = after(2, done) - - - sub.get('/bar', function (req, res, next) { - next(); - }); - - router.param('ms', function (req, res, next, ms) { - ms = parseInt(ms, 10); - req.ms = ms; - setTimeout(next, ms); - }); - - router.use('/foo/:ms/', new Router()); - router.use('/foo/:ms/', sub); - - router.handle(req1, {}, function (err) { - assert.ifError(err); - assert.equal(req1.ms, 50); - assert.equal(req1.originalUrl, '/foo/50/bar'); + describe('.param', () => { + it('should require function', () => { + const router = new Router() + assert.throws(router.param.bind(router, 'id'), /argument fn is required/) + }) + + it('should reject non-function', () => { + const router = new Router() + assert.throws(router.param.bind(router, 'id', 42), /argument fn must be a function/) + }) + + it('should call param function when routing VERBS', (done) => { + const router = new Router() + + router.param('id', (req, res, next, id) => { + assert.equal(id, '123') + next() + }) + + router.get('/foo/:id/bar', (req, res, next) => { + assert.equal(req.params.id, '123') + next() + }) + + router.handle({ url: '/foo/123/bar', method: 'get' }, {}, done) + }) + + it('should call param function when routing middleware', (done) => { + const router = new Router() + + router.param('id', (req, res, next, id) => { + assert.equal(id, '123') + next() + }) + + router.use('/foo/:id/bar', (req, res, next) => { + assert.equal(req.params.id, '123') + assert.equal(req.url, '/baz') + next() + }) + + router.handle({ url: '/foo/123/bar/baz', method: 'get' }, {}, done) + }) + + it('should only call once per request', (done) => { + let count = 0 + const req = { url: '/foo/bob/bar', method: 'get' } + const router = new Router() + const sub = new Router() + + sub.get('/bar', (req, res, next) => { + next() + }) + + router.param('user', (req, res, next, user) => { + count++ + req.user = user + next() + }) + + router.use('/foo/:user/', new Router()) + router.use('/foo/:user/', sub) + + router.handle(req, {}, (err) => { + if (err) return done(err) + assert.equal(count, 1) + assert.equal(req.user, 'bob') + done() + }) + }) + + it('should call when values differ', (done) => { + let count = 0 + const req = { url: '/foo/bob/bar', method: 'get' } + const router = new Router() + const sub = new Router() + + sub.get('/bar', (req, res, next) => { + next() + }) + + router.param('user', (req, res, next, user) => { + count++ + req.user = user + next() + }) + + router.use('/foo/:user/', new Router()) + router.use('/:user/bob/', sub) + + router.handle(req, {}, (err) => { + if (err) return done(err) + assert.equal(count, 2) + assert.equal(req.user, 'foo') + done() + }) + }) + }) + + describe('parallel requests', () => { + it('should not mix requests', (done) => { + const req1 = { url: '/foo/50/bar', method: 'get' } + const req2 = { url: '/foo/10/bar', method: 'get' } + const router = new Router() + const sub = new Router() + const cb = after(2, done) + + sub.get('/bar', (req, res, next) => { + next() + }) + + router.param('ms', (req, res, next, ms) => { + ms = parseInt(ms, 10) + req.ms = ms + setTimeout(next, ms) + }) + + router.use('/foo/:ms/', new Router()) + router.use('/foo/:ms/', sub) + + router.handle(req1, {}, (err) => { + assert.ifError(err) + assert.equal(req1.ms, 50) + assert.equal(req1.originalUrl, '/foo/50/bar') cb() - }); + }) - router.handle(req2, {}, function (err) { - assert.ifError(err); - assert.equal(req2.ms, 10); - assert.equal(req2.originalUrl, '/foo/10/bar'); + router.handle(req2, {}, (err) => { + assert.ifError(err) + assert.equal(req2.ms, 10) + assert.equal(req2.originalUrl, '/foo/10/bar') cb() - }); - }); - }); + }) + }) + }) }) diff --git a/test/acceptance/auth.js b/test/acceptance/auth.js index d7838755a08..1ddd49b48f2 100644 --- a/test/acceptance/auth.js +++ b/test/acceptance/auth.js @@ -1,49 +1,49 @@ -var app = require('../../examples/auth') -var request = require('supertest') +const app = require('../../examples/auth/') +const request = require('supertest') -function getCookie(res) { - return res.headers['set-cookie'][0].split(';')[0]; +function getCookie (res) { + return res.headers['set-cookie'][0].split(';')[0] } -describe('auth', function(){ - describe('GET /',function(){ - it('should redirect to /login', function(done){ +describe('auth', () => { + describe('GET /', () => { + it('should redirect to /login', (done) => { request(app) - .get('/') - .expect('Location', '/login') - .expect(302, done) + .get('/') + .expect('Location', '/login') + .expect(302, done) }) }) - describe('GET /login',function(){ - it('should render login form', function(done){ + describe('GET /login', () => { + it('should render login form', (done) => { request(app) - .get('/login') - .expect(200, /
{ request(app) - .post('/login') - .type('urlencoded') - .send('username=not-tj&password=foobar') - .expect('Location', '/login') - .expect(302, function(err, res){ - if (err) return done(err) - request(app) - .get('/login') - .set('Cookie', getCookie(res)) - .expect(200, /Authentication failed/, done) - }) + .post('/login') + .type('urlencoded') + .send('username=not-tj&password=foobar') + .expect('Location', '/login') + .expect(302, (err, res) => { + if (err) return done(err) + request(app) + .get('/login') + .set('Cookie', getCookie(res)) + .expect(200, /Authentication failed/, done) + }) }) - it('should display login error for bad password', function (done) { + it('should display login error for bad password', (done) => { request(app) .post('/login') .type('urlencoded') .send('username=tj&password=nogood') .expect('Location', '/login') - .expect(302, function (err, res) { + .expect(302, (err, res) => { if (err) return done(err) request(app) .get('/login') @@ -53,65 +53,65 @@ describe('auth', function(){ }) }) - describe('GET /logout',function(){ - it('should redirect to /', function(done){ + describe('GET /logout', () => { + it('should redirect to /', (done) => { request(app) - .get('/logout') - .expect('Location', '/') - .expect(302, done) + .get('/logout') + .expect('Location', '/') + .expect(302, done) }) }) - describe('GET /restricted',function(){ - it('should redirect to /login without cookie', function(done){ + describe('GET /restricted', () => { + it('should redirect to /login without cookie', (done) => { request(app) - .get('/restricted') - .expect('Location', '/login') - .expect(302, done) + .get('/restricted') + .expect('Location', '/login') + .expect(302, done) }) - it('should succeed with proper cookie', function(done){ + it('should succeed with proper cookie', (done) => { request(app) - .post('/login') - .type('urlencoded') - .send('username=tj&password=foobar') - .expect('Location', '/') - .expect(302, function(err, res){ - if (err) return done(err) - request(app) - .get('/restricted') - .set('Cookie', getCookie(res)) - .expect(200, done) - }) + .post('/login') + .type('urlencoded') + .send('username=tj&password=foobar') + .expect('Location', '/') + .expect(302, (err, res) => { + if (err) return done(err) + request(app) + .get('/restricted') + .set('Cookie', getCookie(res)) + .expect(200, done) + }) }) }) - describe('POST /login', function(){ - it('should fail without proper username', function(done){ + describe('POST /login', () => { + it('should fail without proper username', (done) => { request(app) - .post('/login') - .type('urlencoded') - .send('username=not-tj&password=foobar') - .expect('Location', '/login') - .expect(302, done) + .post('/login') + .type('urlencoded') + .send('username=not-tj&password=foobar') + .expect('Location', '/login') + .expect(302, done) }) - it('should fail without proper password', function(done){ + it('should fail without proper password', (done) => { request(app) - .post('/login') - .type('urlencoded') - .send('username=tj&password=baz') - .expect('Location', '/login') - .expect(302, done) + .post('/login') + .type('urlencoded') + .send('username=tj&password=baz') + .expect('Location', '/login') + .expect(302, done) }) - it('should succeed with proper credentials', function(done){ + it('should succeed with proper credentials', (done) => { request(app) - .post('/login') - .type('urlencoded') - .send('username=tj&password=foobar') - .expect('Location', '/') - .expect(302, done) + .post('/login') + .type('urlencoded') + .send('username=tj&password=foobar') + .expect('Location', '/') + .expect(302, done) }) }) }) diff --git a/test/acceptance/content-negotiation.js b/test/acceptance/content-negotiation.js index ac9dbaf557e..961f34bfaea 100644 --- a/test/acceptance/content-negotiation.js +++ b/test/acceptance/content-negotiation.js @@ -1,49 +1,48 @@ +const request = require('supertest') +const app = require('../../examples/content-negotiation/') -var request = require('supertest') - , app = require('../../examples/content-negotiation'); - -describe('content-negotiation', function(){ - describe('GET /', function(){ - it('should default to text/html', function(done){ +describe('content-negotiation', () => { + describe('GET /', () => { + it('should default to text/html', (done) => { request(app) - .get('/') - .expect(200, '
  • Tobi
  • Loki
  • Jane
', done) + .get('/') + .expect(200, '
  • Tobi
  • Loki
  • Jane
', done) }) - it('should accept to text/plain', function(done){ + it('should accept to text/plain', (done) => { request(app) - .get('/') - .set('Accept', 'text/plain') - .expect(200, ' - Tobi\n - Loki\n - Jane\n', done) + .get('/') + .set('Accept', 'text/plain') + .expect(200, ' - Tobi\n - Loki\n - Jane\n', done) }) - it('should accept to application/json', function(done){ + it('should accept to application/json', (done) => { request(app) - .get('/') - .set('Accept', 'application/json') - .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done) + .get('/') + .set('Accept', 'application/json') + .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done) }) }) - describe('GET /users', function(){ - it('should default to text/html', function(done){ + describe('GET /users', () => { + it('should default to text/html', (done) => { request(app) - .get('/users') - .expect(200, '
  • Tobi
  • Loki
  • Jane
', done) + .get('/users') + .expect(200, '
  • Tobi
  • Loki
  • Jane
', done) }) - it('should accept to text/plain', function(done){ + it('should accept to text/plain', (done) => { request(app) - .get('/users') - .set('Accept', 'text/plain') - .expect(200, ' - Tobi\n - Loki\n - Jane\n', done) + .get('/users') + .set('Accept', 'text/plain') + .expect(200, ' - Tobi\n - Loki\n - Jane\n', done) }) - it('should accept to application/json', function(done){ + it('should accept to application/json', (done) => { request(app) - .get('/users') - .set('Accept', 'application/json') - .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done) + .get('/users') + .set('Accept', 'application/json') + .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done) }) }) }) diff --git a/test/acceptance/cookie-sessions.js b/test/acceptance/cookie-sessions.js index e83c8e419da..59db5a50c41 100644 --- a/test/acceptance/cookie-sessions.js +++ b/test/acceptance/cookie-sessions.js @@ -1,38 +1,35 @@ +const app = require('../../examples/cookie-sessions/') +const request = require('supertest') -var app = require('../../examples/cookie-sessions') -var request = require('supertest') - -describe('cookie-sessions', function () { - describe('GET /', function () { - it('should display no views', function (done) { +describe('cookie-sessions', () => { + describe('GET /', () => { + it('should display no views', (done) => { request(app) - .get('/') - .expect(200, 'viewed 1 times\n', done) + .get('/') + .expect(200, 'viewed 1 times\n', done) }) - it('should set a session cookie', function (done) { + it('should set a session cookie', (done) => { request(app) - .get('/') - .expect('Set-Cookie', /session=/) - .expect(200, done) + .get('/') + .expect('Set-Cookie', /session=/) + .expect(200, done) }) - it('should display 1 view on revisit', function (done) { + it('should display 1 view on revisit', (done) => { request(app) - .get('/') - .expect(200, 'viewed 1 times\n', function (err, res) { - if (err) return done(err) - request(app) .get('/') - .set('Cookie', getCookies(res)) - .expect(200, 'viewed 2 times\n', done) - }) + .expect(200, 'viewed 1 times\n', (err, res) => { + if (err) return done(err) + request(app) + .get('/') + .set('Cookie', getCookies(res)) + .expect(200, 'viewed 2 times\n', done) + }) }) }) }) -function getCookies(res) { - return res.headers['set-cookie'].map(function (val) { - return val.split(';')[0] - }).join('; '); +function getCookies (res) { + return res.headers['set-cookie'].map((val) => val.split(';')[0]).join('; ') } diff --git a/test/acceptance/cookies.js b/test/acceptance/cookies.js index aa9e1faef44..fec3b9276c5 100644 --- a/test/acceptance/cookies.js +++ b/test/acceptance/cookies.js @@ -1,71 +1,70 @@ +const app = require('../../examples/cookies/') +const request = require('supertest') +const utils = require('../support/utils') -var app = require('../../examples/cookies') - , request = require('supertest'); -var utils = require('../support/utils'); - -describe('cookies', function(){ - describe('GET /', function(){ - it('should have a form', function(done){ +describe('cookies', () => { + describe('GET /', () => { + it('should have a form', (done) => { request(app) - .get('/') - .expect(/ { request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('Set-Cookie')) - .expect(200, done) + .get('/') + .expect(utils.shouldNotHaveHeader('Set-Cookie')) + .expect(200, done) }) - it('should respond to cookie', function(done){ + it('should respond to cookie', (done) => { request(app) - .post('/') - .type('urlencoded') - .send({ remember: 1 }) - .expect(302, function(err, res){ - if (err) return done(err) - request(app) - .get('/') - .set('Cookie', res.headers['set-cookie'][0]) - .expect(200, /Remembered/, done) - }) + .post('/') + .type('urlencoded') + .send({ remember: 1 }) + .expect(302, (err, res) => { + if (err) return done(err) + request(app) + .get('/') + .set('Cookie', res.headers['set-cookie'][0]) + .expect(200, /Remembered/, done) + }) }) }) - describe('GET /forget', function(){ - it('should clear cookie', function(done){ + describe('GET /forget', () => { + it('should clear cookie', (done) => { request(app) - .post('/') - .type('urlencoded') - .send({ remember: 1 }) - .expect(302, function(err, res){ - if (err) return done(err) - request(app) - .get('/forget') - .set('Cookie', res.headers['set-cookie'][0]) - .expect('Set-Cookie', /remember=;/) - .expect(302, done) - }) + .post('/') + .type('urlencoded') + .send({ remember: 1 }) + .expect(302, (err, res) => { + if (err) return done(err) + request(app) + .get('/forget') + .set('Cookie', res.headers['set-cookie'][0]) + .expect('Set-Cookie', /remember=;/) + .expect(302, done) + }) }) }) - describe('POST /', function(){ - it('should set a cookie', function(done){ + describe('POST /', () => { + it('should set a cookie', (done) => { request(app) - .post('/') - .type('urlencoded') - .send({ remember: 1 }) - .expect('Set-Cookie', /remember=1/) - .expect(302, done) + .post('/') + .type('urlencoded') + .send({ remember: 1 }) + .expect('Set-Cookie', /remember=1/) + .expect(302, done) }) - it('should no set cookie w/o reminder', function(done){ + it('should no set cookie w/o reminder', (done) => { request(app) - .post('/') - .send({}) - .expect(utils.shouldNotHaveHeader('Set-Cookie')) - .expect(302, done) + .post('/') + .send({}) + .expect(utils.shouldNotHaveHeader('Set-Cookie')) + .expect(302, done) }) }) }) diff --git a/test/acceptance/downloads.js b/test/acceptance/downloads.js index 6db43b351e4..f2a55e97499 100644 --- a/test/acceptance/downloads.js +++ b/test/acceptance/downloads.js @@ -1,18 +1,17 @@ +const app = require('../../examples/downloads/') +const request = require('supertest') -var app = require('../../examples/downloads') - , request = require('supertest'); - -describe('downloads', function(){ - describe('GET /', function(){ - it('should have a link to amazing.txt', function(done){ +describe('downloads', () => { + describe('GET /', () => { + it('should have a link to amazing.txt', (done) => { request(app) - .get('/') - .expect(/href="\/files\/amazing.txt"/, done) + .get('/') + .expect(/href="\/files\/amazing.txt"/, done) }) }) - describe('GET /files/notes/groceries.txt', function () { - it('should have a download header', function (done) { + describe('GET /files/notes/groceries.txt', () => { + it('should have a download header', (done) => { request(app) .get('/files/notes/groceries.txt') .expect('Content-Disposition', 'attachment; filename="groceries.txt"') @@ -20,25 +19,25 @@ describe('downloads', function(){ }) }) - describe('GET /files/amazing.txt', function(){ - it('should have a download header', function(done){ + describe('GET /files/amazing.txt', () => { + it('should have a download header', (done) => { request(app) - .get('/files/amazing.txt') - .expect('Content-Disposition', 'attachment; filename="amazing.txt"') - .expect(200, done) + .get('/files/amazing.txt') + .expect('Content-Disposition', 'attachment; filename="amazing.txt"') + .expect(200, done) }) }) - describe('GET /files/missing.txt', function(){ - it('should respond with 404', function(done){ + describe('GET /files/missing.txt', () => { + it('should respond with 404', (done) => { request(app) - .get('/files/missing.txt') - .expect(404, done) + .get('/files/missing.txt') + .expect(404, done) }) }) - describe('GET /files/../index.js', function () { - it('should respond with 403', function (done) { + describe('GET /files/../index.js', () => { + it('should respond with 403', (done) => { request(app) .get('/files/../index.js') .expect(403, done) diff --git a/test/acceptance/ejs.js b/test/acceptance/ejs.js index 12defcb564f..df3a1c27704 100644 --- a/test/acceptance/ejs.js +++ b/test/acceptance/ejs.js @@ -1,17 +1,16 @@ +const request = require('supertest') +const app = require('../../examples/ejs/') -var request = require('supertest') - , app = require('../../examples/ejs'); - -describe('ejs', function(){ - describe('GET /', function(){ - it('should respond with html', function(done){ +describe('ejs', () => { + describe('GET /', () => { + it('should respond with html', (done) => { request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect(/
  • tobi <tobi@learnboost\.com><\/li>/) - .expect(/
  • loki <loki@learnboost\.com><\/li>/) - .expect(/
  • jane <jane@learnboost\.com><\/li>/) - .expect(200, done) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect(/
  • tobi <tobi@learnboost\.com><\/li>/) + .expect(/
  • loki <loki@learnboost\.com><\/li>/) + .expect(/
  • jane <jane@learnboost\.com><\/li>/) + .expect(200, done) }) }) }) diff --git a/test/acceptance/error-pages.js b/test/acceptance/error-pages.js index 48feb3fb466..1fddbd3cfed 100644 --- a/test/acceptance/error-pages.js +++ b/test/acceptance/error-pages.js @@ -1,98 +1,96 @@ +const app = require('../../examples/error-pages/') +const request = require('supertest') -var app = require('../../examples/error-pages') - , request = require('supertest'); - -describe('error-pages', function(){ - describe('GET /', function(){ - it('should respond with page list', function(done){ +describe('error-pages', () => { + describe('GET /', () => { + it('should respond with page list', (done) => { request(app) - .get('/') - .expect(/Pages Example/, done) + .get('/') + .expect(/Pages Example/, done) }) }) - describe('Accept: text/html',function(){ - describe('GET /403', function(){ - it('should respond with 403', function(done){ + describe('Accept: text/html', () => { + describe('GET /403', () => { + it('should respond with 403', (done) => { request(app) - .get('/403') - .expect(403, done) + .get('/403') + .expect(403, done) }) }) - describe('GET /404', function(){ - it('should respond with 404', function(done){ + describe('GET /404', () => { + it('should respond with 404', (done) => { request(app) - .get('/404') - .expect(404, done) + .get('/404') + .expect(404, done) }) }) - describe('GET /500', function(){ - it('should respond with 500', function(done){ + describe('GET /500', () => { + it('should respond with 500', (done) => { request(app) - .get('/500') - .expect(500, done) + .get('/500') + .expect(500, done) }) }) }) - describe('Accept: application/json',function(){ - describe('GET /403', function(){ - it('should respond with 403', function(done){ + describe('Accept: application/json', () => { + describe('GET /403', () => { + it('should respond with 403', (done) => { request(app) - .get('/403') - .set('Accept','application/json') - .expect(403, done) + .get('/403') + .set('Accept', 'application/json') + .expect(403, done) }) }) - describe('GET /404', function(){ - it('should respond with 404', function(done){ + describe('GET /404', () => { + it('should respond with 404', (done) => { request(app) - .get('/404') - .set('Accept','application/json') - .expect(404, { error: 'Not found' }, done) + .get('/404') + .set('Accept', 'application/json') + .expect(404, { error: 'Not found' }, done) }) }) - describe('GET /500', function(){ - it('should respond with 500', function(done){ + describe('GET /500', () => { + it('should respond with 500', (done) => { request(app) - .get('/500') - .set('Accept', 'application/json') - .expect(500, done) + .get('/500') + .set('Accept', 'application/json') + .expect(500, done) }) }) }) - - describe('Accept: text/plain',function(){ - describe('GET /403', function(){ - it('should respond with 403', function(done){ + describe('Accept: text/plain', () => { + describe('GET /403', () => { + it('should respond with 403', (done) => { request(app) - .get('/403') - .set('Accept','text/plain') - .expect(403, done) + .get('/403') + .set('Accept', 'text/plain') + .expect(403, done) }) }) - describe('GET /404', function(){ - it('should respond with 404', function(done){ + describe('GET /404', () => { + it('should respond with 404', (done) => { request(app) - .get('/404') - .set('Accept', 'text/plain') - .expect(404) - .expect('Not found', done); + .get('/404') + .set('Accept', 'text/plain') + .expect(404) + .expect('Not found', done) }) }) - describe('GET /500', function(){ - it('should respond with 500', function(done){ + describe('GET /500', () => { + it('should respond with 500', (done) => { request(app) - .get('/500') - .set('Accept','text/plain') - .expect(500, done) + .get('/500') + .set('Accept', 'text/plain') + .expect(500, done) }) }) }) diff --git a/test/acceptance/error.js b/test/acceptance/error.js index 6bdf099feed..c28b4724bea 100644 --- a/test/acceptance/error.js +++ b/test/acceptance/error.js @@ -1,29 +1,28 @@ +const app = require('../../examples/error/') +const request = require('supertest') -var app = require('../../examples/error') - , request = require('supertest'); - -describe('error', function(){ - describe('GET /', function(){ - it('should respond with 500', function(done){ +describe('error', () => { + describe('GET /', () => { + it('should respond with 500', (done) => { request(app) .get('/') - .expect(500,done) + .expect(500, done) }) }) - describe('GET /next', function(){ - it('should respond with 500', function(done){ + describe('GET /next', () => { + it('should respond with 500', (done) => { request(app) .get('/next') - .expect(500,done) + .expect(500, done) }) }) - describe('GET /missing', function(){ - it('should respond with 404', function(done){ + describe('GET /missing', () => { + it('should respond with 404', (done) => { request(app) .get('/missing') - .expect(404,done) + .expect(404, done) }) }) }) diff --git a/test/acceptance/hello-world.js b/test/acceptance/hello-world.js index db90349c496..797cfd739bc 100644 --- a/test/acceptance/hello-world.js +++ b/test/acceptance/hello-world.js @@ -1,18 +1,17 @@ +const app = require('../../examples/hello-world/') +const request = require('supertest') -var app = require('../../examples/hello-world') -var request = require('supertest') - -describe('hello-world', function () { - describe('GET /', function () { - it('should respond with hello world', function (done) { +describe('hello-world', () => { + describe('GET /', () => { + it('should respond with hello world', (done) => { request(app) .get('/') .expect(200, 'Hello World', done) }) }) - describe('GET /missing', function () { - it('should respond with 404', function (done) { + describe('GET /missing', () => { + it('should respond with 404', (done) => { request(app) .get('/missing') .expect(404, done) diff --git a/test/acceptance/markdown.js b/test/acceptance/markdown.js index 1a7d9e3cb75..34e31fb41f3 100644 --- a/test/acceptance/markdown.js +++ b/test/acceptance/markdown.js @@ -1,21 +1,20 @@ +const app = require('../../examples/markdown/') +const request = require('supertest') -var app = require('../../examples/markdown') -var request = require('supertest') - -describe('markdown', function(){ - describe('GET /', function(){ - it('should respond with html', function(done){ +describe('markdown', () => { + describe('GET /', () => { + it('should respond with html', (done) => { request(app) .get('/') - .expect(/]*>Markdown Example<\/h1>/,done) + .expect(/]*>Markdown Example<\/h1>/, done) }) }) - describe('GET /fail',function(){ - it('should respond with an error', function(done){ + describe('GET /fail', () => { + it('should respond with an error', (done) => { request(app) .get('/fail') - .expect(500,done) + .expect(500, done) }) }) }) diff --git a/test/acceptance/multi-router.js b/test/acceptance/multi-router.js index 4362a8300be..afb5fe6a52a 100644 --- a/test/acceptance/multi-router.js +++ b/test/acceptance/multi-router.js @@ -1,44 +1,44 @@ -var app = require('../../examples/multi-router') -var request = require('supertest') +const app = require('../../examples/multi-router/') +const request = require('supertest') -describe('multi-router', function(){ - describe('GET /',function(){ - it('should respond with root handler', function(done){ +describe('multi-router', () => { + describe('GET /', () => { + it('should respond with root handler', (done) => { request(app) - .get('/') - .expect(200, 'Hello from root route.', done) + .get('/') + .expect(200, 'Hello from root route.', done) }) }) - describe('GET /api/v1/',function(){ - it('should respond with APIv1 root handler', function(done){ + describe('GET /api/v1/', () => { + it('should respond with APIv1 root handler', (done) => { request(app) - .get('/api/v1/') - .expect(200, 'Hello from APIv1 root route.', done) + .get('/api/v1/') + .expect(200, 'Hello from APIv1 root route.', done) }) }) - describe('GET /api/v1/users',function(){ - it('should respond with users from APIv1', function(done){ + describe('GET /api/v1/users', () => { + it('should respond with users from APIv1', (done) => { request(app) - .get('/api/v1/users') - .expect(200, 'List of APIv1 users.', done) + .get('/api/v1/users') + .expect(200, 'List of APIv1 users.', done) }) }) - describe('GET /api/v2/',function(){ - it('should respond with APIv2 root handler', function(done){ + describe('GET /api/v2/', () => { + it('should respond with APIv2 root handler', (done) => { request(app) - .get('/api/v2/') - .expect(200, 'Hello from APIv2 root route.', done) + .get('/api/v2/') + .expect(200, 'Hello from APIv2 root route.', done) }) }) - describe('GET /api/v2/users',function(){ - it('should respond with users from APIv2', function(done){ + describe('GET /api/v2/users', () => { + it('should respond with users from APIv2', (done) => { request(app) - .get('/api/v2/users') - .expect(200, 'List of APIv2 users.', done) + .get('/api/v2/users') + .expect(200, 'List of APIv2 users.', done) }) }) }) diff --git a/test/acceptance/mvc.js b/test/acceptance/mvc.js index 35709f6fb46..8a777a664ac 100644 --- a/test/acceptance/mvc.js +++ b/test/acceptance/mvc.js @@ -1,132 +1,131 @@ +const request = require('supertest') +const app = require('../../examples/mvc/') -var request = require('supertest') - , app = require('../../examples/mvc'); - -describe('mvc', function(){ - describe('GET /', function(){ - it('should redirect to /users', function(done){ +describe('mvc', () => { + describe('GET /', () => { + it('should redirect to /users', (done) => { request(app) - .get('/') - .expect('Location', '/users') - .expect(302, done) + .get('/') + .expect('Location', '/users') + .expect(302, done) }) }) - describe('GET /pet/0', function(){ - it('should get pet', function(done){ + describe('GET /pet/0', () => { + it('should get pet', (done) => { request(app) - .get('/pet/0') - .expect(200, /Tobi/, done) + .get('/pet/0') + .expect(200, /Tobi/, done) }) }) - describe('GET /pet/0/edit', function(){ - it('should get pet edit page', function(done){ + describe('GET /pet/0/edit', () => { + it('should get pet edit page', (done) => { request(app) - .get('/pet/0/edit') - .expect(/ { + it('should update the pet', (done) => { request(app) - .put('/pet/3') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send({ pet: { name: 'Boots' } }) - .expect(302, function (err, res) { - if (err) return done(err); - request(app) - .get('/pet/3/edit') - .expect(200, /Boots/, done) - }) + .put('/pet/3') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send({ pet: { name: 'Boots' } }) + .expect(302, (err, res) => { + if (err) return done(err) + request(app) + .get('/pet/3/edit') + .expect(200, /Boots/, done) + }) }) }) - describe('GET /users', function(){ - it('should display a list of users', function(done){ + describe('GET /users', () => { + it('should display a list of users', (done) => { request(app) - .get('/users') - .expect(/

    Users<\/h1>/) - .expect(/>TJGuillermoNathanUsers<\/h1>/) + .expect(/>TJGuillermoNathan { + describe('when present', () => { + it('should display the user', (done) => { request(app) - .get('/user/0') - .expect(200, /

    TJ edit/, done) + .get('/user/0') + .expect(200, /

    TJ edit/, done) }) - it('should display the users pets', function(done){ + it('should display the users pets', (done) => { request(app) - .get('/user/0') - .expect(/\/pet\/0">Tobi/) - .expect(/\/pet\/1">Loki/) - .expect(/\/pet\/2">Jane/) - .expect(200, done) + .get('/user/0') + .expect(/\/pet\/0">Tobi/) + .expect(/\/pet\/1">Loki/) + .expect(/\/pet\/2">Jane/) + .expect(200, done) }) }) - describe('when not present', function(){ - it('should 404', function(done){ + describe('when not present', () => { + it('should 404', (done) => { request(app) - .get('/user/123') - .expect(404, done); + .get('/user/123') + .expect(404, done) }) }) }) - describe('GET /user/:id/edit', function(){ - it('should display the edit form', function(done){ + describe('GET /user/:id/edit', () => { + it('should display the edit form', (done) => { request(app) - .get('/user/1/edit') - .expect(/Guillermo/) - .expect(200, / { + it('should 500 on error', (done) => { request(app) - .put('/user/1') - .send({}) - .expect(500, done) + .put('/user/1') + .send({}) + .expect(500, done) }) - it('should update the user', function(done){ + it('should update the user', (done) => { request(app) - .put('/user/1') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send({ user: { name: 'Tobo' }}) - .expect(302, function (err, res) { - if (err) return done(err); - request(app) - .get('/user/1/edit') - .expect(200, /Tobo/, done) - }) + .put('/user/1') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send({ user: { name: 'Tobo' } }) + .expect(302, (err, res) => { + if (err) return done(err) + request(app) + .get('/user/1/edit') + .expect(200, /Tobo/, done) + }) }) }) - describe('POST /user/:id/pet', function(){ - it('should create a pet for user', function(done){ + describe('POST /user/:id/pet', () => { + it('should create a pet for user', (done) => { request(app) - .post('/user/2/pet') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send({ pet: { name: 'Snickers' }}) - .expect('Location', '/user/2') - .expect(302, function(err, res){ - if (err) return done(err) - request(app) - .get('/user/2') - .expect(200, /Snickers/, done) - }) + .post('/user/2/pet') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send({ pet: { name: 'Snickers' } }) + .expect('Location', '/user/2') + .expect(302, (err, res) => { + if (err) return done(err) + request(app) + .get('/user/2') + .expect(200, /Snickers/, done) + }) }) }) }) diff --git a/test/acceptance/params.js b/test/acceptance/params.js index e7c30cf7732..c98bd6afe5f 100644 --- a/test/acceptance/params.js +++ b/test/acceptance/params.js @@ -1,44 +1,44 @@ -var app = require('../../examples/params') -var request = require('supertest') +const app = require('../../examples/params/') +const request = require('supertest') -describe('params', function(){ - describe('GET /', function(){ - it('should respond with instructions', function(done){ +describe('params', () => { + describe('GET /', () => { + it('should respond with instructions', (done) => { request(app) .get('/') - .expect(/Visit/,done) + .expect(/Visit/, done) }) }) - describe('GET /user/0', function(){ - it('should respond with a user', function(done){ + describe('GET /user/0', () => { + it('should respond with a user', (done) => { request(app) .get('/user/0') - .expect(/user tj/,done) + .expect(/user tj/, done) }) }) - describe('GET /user/9', function(){ - it('should fail to find user', function(done){ + describe('GET /user/9', () => { + it('should fail to find user', (done) => { request(app) - .get('/user/9') - .expect(404, /failed to find user/, done) + .get('/user/9') + .expect(404, /failed to find user/, done) }) }) - describe('GET /users/0-2', function(){ - it('should respond with three users', function(done){ + describe('GET /users/0-2', () => { + it('should respond with three users', (done) => { request(app) - .get('/users/0-2') - .expect(/users tj, tobi, loki/, done) + .get('/users/0-2') + .expect(/users tj, tobi, loki/, done) }) }) - describe('GET /users/foo-bar', function(){ - it('should fail integer parsing', function(done){ + describe('GET /users/foo-bar', () => { + it('should fail integer parsing', (done) => { request(app) - .get('/users/foo-bar') - .expect(400, /failed to parseInt foo/, done) + .get('/users/foo-bar') + .expect(400, /failed to parseInt foo/, done) }) }) }) diff --git a/test/acceptance/resource.js b/test/acceptance/resource.js index a2db7bd3fd2..ecc69b6d30e 100644 --- a/test/acceptance/resource.js +++ b/test/acceptance/resource.js @@ -1,68 +1,68 @@ -var app = require('../../examples/resource') -var request = require('supertest') +const app = require('../../examples/resource/') +const request = require('supertest') -describe('resource', function(){ - describe('GET /', function(){ - it('should respond with instructions', function(done){ +describe('resource', () => { + describe('GET /', () => { + it('should respond with instructions', (done) => { request(app) .get('/') - .expect(/^

    Examples:<\/h1>/,done) + .expect(/^

    Examples:<\/h1>/, done) }) }) - describe('GET /users', function(){ - it('should respond with all users', function(done){ + describe('GET /users', () => { + it('should respond with all users', (done) => { request(app) .get('/users') - .expect(/^\[{"name":"tj"},{"name":"ciaran"},{"name":"aaron"},{"name":"guillermo"},{"name":"simon"},{"name":"tobi"}\]/,done) + .expect(/^\[{"name":"tj"},{"name":"ciaran"},{"name":"aaron"},{"name":"guillermo"},{"name":"simon"},{"name":"tobi"}\]/, done) }) }) - describe('GET /users/1', function(){ - it('should respond with user 1', function(done){ + describe('GET /users/1', () => { + it('should respond with user 1', (done) => { request(app) .get('/users/1') - .expect(/^{"name":"ciaran"}/,done) + .expect(/^{"name":"ciaran"}/, done) }) }) - describe('GET /users/9', function(){ - it('should respond with error', function(done){ + describe('GET /users/9', () => { + it('should respond with error', (done) => { request(app) .get('/users/9') .expect('{"error":"Cannot find user"}', done) }) }) - describe('GET /users/1..3', function(){ - it('should respond with users 1 through 3', function(done){ + describe('GET /users/1..3', () => { + it('should respond with users 1 through 3', (done) => { request(app) .get('/users/1..3') - .expect(/^
    • ciaran<\/li>\n
    • aaron<\/li>\n
    • guillermo<\/li><\/ul>/,done) + .expect(/^
      • ciaran<\/li>\n
      • aaron<\/li>\n
      • guillermo<\/li><\/ul>/, done) }) }) - describe('DELETE /users/1', function(){ - it('should delete user 1', function(done){ + describe('DELETE /users/1', () => { + it('should delete user 1', (done) => { request(app) .del('/users/1') - .expect(/^destroyed/,done) + .expect(/^destroyed/, done) }) }) - describe('DELETE /users/9', function(){ - it('should fail', function(done){ + describe('DELETE /users/9', () => { + it('should fail', (done) => { request(app) .del('/users/9') .expect('Cannot find user', done) }) }) - describe('GET /users/1..3.json', function(){ - it('should respond with users 2 and 3 as json', function(done){ + describe('GET /users/1..3.json', () => { + it('should respond with users 2 and 3 as json', (done) => { request(app) .get('/users/1..3.json') - .expect(/^\[null,{"name":"aaron"},{"name":"guillermo"}\]/,done) + .expect(/^\[null,{"name":"aaron"},{"name":"guillermo"}\]/, done) }) }) }) diff --git a/test/acceptance/route-map.js b/test/acceptance/route-map.js index 0bd2a6d32e1..7b79fe3c33b 100644 --- a/test/acceptance/route-map.js +++ b/test/acceptance/route-map.js @@ -1,45 +1,44 @@ +const request = require('supertest') +const app = require('../../examples/route-map/') -var request = require('supertest') - , app = require('../../examples/route-map'); - -describe('route-map', function(){ - describe('GET /users', function(){ - it('should respond with users', function(done){ +describe('route-map', () => { + describe('GET /users', () => { + it('should respond with users', (done) => { request(app) - .get('/users') - .expect('user list', done); + .get('/users') + .expect('user list', done) }) }) - describe('DELETE /users', function(){ - it('should delete users', function(done){ + describe('DELETE /users', () => { + it('should delete users', (done) => { request(app) - .del('/users') - .expect('delete users', done); + .del('/users') + .expect('delete users', done) }) }) - describe('GET /users/:id', function(){ - it('should get a user', function(done){ + describe('GET /users/:id', () => { + it('should get a user', (done) => { request(app) - .get('/users/12') - .expect('user 12', done); + .get('/users/12') + .expect('user 12', done) }) }) - describe('GET /users/:id/pets', function(){ - it('should get a users pets', function(done){ + describe('GET /users/:id/pets', () => { + it('should get a users pets', (done) => { request(app) - .get('/users/12/pets') - .expect('user 12\'s pets', done); + .get('/users/12/pets') + .expect('user 12\'s pets', done) }) }) - describe('GET /users/:id/pets/:pid', function(){ - it('should get a users pet', function(done){ + describe('GET /users/:id/pets/:pid', () => { + it('should get a users pet', (done) => { request(app) - .del('/users/12/pets/2') - .expect('delete 12\'s pet 2', done); + .del('/users/12/pets/2') + .expect('delete 12\'s pet 2', done) }) }) }) diff --git a/test/acceptance/route-separation.js b/test/acceptance/route-separation.js index 867fd295271..bf2b72fc25b 100644 --- a/test/acceptance/route-separation.js +++ b/test/acceptance/route-separation.js @@ -1,97 +1,96 @@ +const app = require('../../examples/route-separation/') +const request = require('supertest') -var app = require('../../examples/route-separation') -var request = require('supertest') - -describe('route-separation', function () { - describe('GET /', function () { - it('should respond with index', function (done) { +describe('route-separation', () => { + describe('GET /', () => { + it('should respond with index', (done) => { request(app) - .get('/') - .expect(200, /Route Separation Example/, done) + .get('/') + .expect(200, /Route Separation Example/, done) }) }) - describe('GET /users', function () { - it('should list users', function (done) { + describe('GET /users', () => { + it('should list users', (done) => { request(app) - .get('/users') - .expect(/TJ/) - .expect(/Tobi/) - .expect(200, done) + .get('/users') + .expect(/TJ/) + .expect(/Tobi/) + .expect(200, done) }) }) - describe('GET /user/:id', function () { - it('should get a user', function (done) { + describe('GET /user/:id', () => { + it('should get a user', (done) => { request(app) - .get('/user/0') - .expect(200, /Viewing user TJ/, done) + .get('/user/0') + .expect(200, /Viewing user TJ/, done) }) - it('should 404 on missing user', function (done) { + it('should 404 on missing user', (done) => { request(app) - .get('/user/10') - .expect(404, done) + .get('/user/10') + .expect(404, done) }) }) - describe('GET /user/:id/view', function () { - it('should get a user', function (done) { + describe('GET /user/:id/view', () => { + it('should get a user', (done) => { request(app) - .get('/user/0/view') - .expect(200, /Viewing user TJ/, done) + .get('/user/0/view') + .expect(200, /Viewing user TJ/, done) }) - it('should 404 on missing user', function (done) { + it('should 404 on missing user', (done) => { request(app) - .get('/user/10/view') - .expect(404, done) + .get('/user/10/view') + .expect(404, done) }) }) - describe('GET /user/:id/edit', function () { - it('should get a user to edit', function (done) { + describe('GET /user/:id/edit', () => { + it('should get a user to edit', (done) => { request(app) - .get('/user/0/edit') - .expect(200, /Editing user TJ/, done) + .get('/user/0/edit') + .expect(200, /Editing user TJ/, done) }) }) - describe('PUT /user/:id/edit', function () { - it('should edit a user', function (done) { + describe('PUT /user/:id/edit', () => { + it('should edit a user', (done) => { request(app) - .put('/user/0/edit') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send({ user: { name: 'TJ', email: 'tj-invalid@vision-media.ca' } }) - .expect(302, function (err) { - if (err) return done(err) - request(app) - .get('/user/0') - .expect(200, /tj-invalid@vision-media\.ca/, done) - }) + .put('/user/0/edit') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send({ user: { name: 'TJ', email: 'tj-invalid@vision-media.ca' } }) + .expect(302, (err) => { + if (err) return done(err) + request(app) + .get('/user/0') + .expect(200, /tj-invalid@vision-media\.ca/, done) + }) }) }) - describe('POST /user/:id/edit?_method=PUT', function () { - it('should edit a user', function (done) { + describe('POST /user/:id/edit?_method=PUT', () => { + it('should edit a user', (done) => { request(app) - .post('/user/1/edit?_method=PUT') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send({ user: { name: 'Tobi', email: 'tobi-invalid@vision-media.ca' } }) - .expect(302, function (err) { - if (err) return done(err) - request(app) - .get('/user/1') - .expect(200, /tobi-invalid@vision-media\.ca/, done) - }) + .post('/user/1/edit?_method=PUT') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send({ user: { name: 'Tobi', email: 'tobi-invalid@vision-media.ca' } }) + .expect(302, (err) => { + if (err) return done(err) + request(app) + .get('/user/1') + .expect(200, /tobi-invalid@vision-media\.ca/, done) + }) }) }) - describe('GET /posts', function () { - it('should get a list of posts', function (done) { + describe('GET /posts', () => { + it('should get a list of posts', (done) => { request(app) - .get('/posts') - .expect(200, /Posts/, done) + .get('/posts') + .expect(200, /Posts/, done) }) }) }) diff --git a/test/acceptance/vhost.js b/test/acceptance/vhost.js index 1b633d4b2bc..a7cac6b12f7 100644 --- a/test/acceptance/vhost.js +++ b/test/acceptance/vhost.js @@ -1,45 +1,45 @@ -var app = require('../../examples/vhost') -var request = require('supertest') +const app = require('../../examples/vhost/') +const request = require('supertest') -describe('vhost', function(){ - describe('example.com', function(){ - describe('GET /', function(){ - it('should say hello', function(done){ +describe('vhost', () => { + describe('example.com', () => { + describe('GET /', () => { + it('should say hello', (done) => { request(app) - .get('/') - .set('Host', 'example.com') - .expect(200, /hello/i, done) + .get('/') + .set('Host', 'example.com') + .expect(200, /hello/i, done) }) }) - describe('GET /foo', function(){ - it('should say foo', function(done){ + describe('GET /foo', () => { + it('should say foo', (done) => { request(app) - .get('/foo') - .set('Host', 'example.com') - .expect(200, 'requested foo', done) + .get('/foo') + .set('Host', 'example.com') + .expect(200, 'requested foo', done) }) }) }) - describe('foo.example.com', function(){ - describe('GET /', function(){ - it('should redirect to /foo', function(done){ + describe('foo.example.com', () => { + describe('GET /', () => { + it('should redirect to /foo', (done) => { request(app) - .get('/') - .set('Host', 'foo.example.com') - .expect(302, /Redirecting to http:\/\/example.com:3000\/foo/, done) + .get('/') + .set('Host', 'foo.example.com') + .expect(302, /Redirecting to http:\/\/example.com:3000\/foo/, done) }) }) }) - describe('bar.example.com', function(){ - describe('GET /', function(){ - it('should redirect to /bar', function(done){ + describe('bar.example.com', () => { + describe('GET /', () => { + it('should redirect to /bar', (done) => { request(app) - .get('/') - .set('Host', 'bar.example.com') - .expect(302, /Redirecting to http:\/\/example.com:3000\/bar/, done) + .get('/') + .set('Host', 'bar.example.com') + .expect(302, /Redirecting to http:\/\/example.com:3000\/bar/, done) }) }) }) diff --git a/test/acceptance/web-service.js b/test/acceptance/web-service.js index 2e37b48c8ca..06c0e040f92 100644 --- a/test/acceptance/web-service.js +++ b/test/acceptance/web-service.js @@ -1,101 +1,100 @@ +const request = require('supertest') +const app = require('../../examples/web-service/') -var request = require('supertest') - , app = require('../../examples/web-service'); - -describe('web-service', function(){ - describe('GET /api/users', function(){ - describe('without an api key', function(){ - it('should respond with 400 bad request', function(done){ +describe('web-service', () => { + describe('GET /api/users', () => { + describe('without an api key', () => { + it('should respond with 400 bad request', (done) => { request(app) - .get('/api/users') - .expect(400, done); + .get('/api/users') + .expect(400, done) }) }) - describe('with an invalid api key', function(){ - it('should respond with 401 unauthorized', function(done){ + describe('with an invalid api key', () => { + it('should respond with 401 unauthorized', (done) => { request(app) - .get('/api/users?api-key=rawr') - .expect(401, done); + .get('/api/users?api-key=rawr') + .expect(401, done) }) }) - describe('with a valid api key', function(){ - it('should respond users json', function(done){ + describe('with a valid api key', () => { + it('should respond users json', (done) => { request(app) - .get('/api/users?api-key=foo') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '[{"name":"tobi"},{"name":"loki"},{"name":"jane"}]', done) + .get('/api/users?api-key=foo') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '[{"name":"tobi"},{"name":"loki"},{"name":"jane"}]', done) }) }) }) - describe('GET /api/repos', function(){ - describe('without an api key', function(){ - it('should respond with 400 bad request', function(done){ + describe('GET /api/repos', () => { + describe('without an api key', () => { + it('should respond with 400 bad request', (done) => { request(app) - .get('/api/repos') - .expect(400, done); + .get('/api/repos') + .expect(400, done) }) }) - describe('with an invalid api key', function(){ - it('should respond with 401 unauthorized', function(done){ + describe('with an invalid api key', () => { + it('should respond with 401 unauthorized', (done) => { request(app) - .get('/api/repos?api-key=rawr') - .expect(401, done); + .get('/api/repos?api-key=rawr') + .expect(401, done) }) }) - describe('with a valid api key', function(){ - it('should respond repos json', function(done){ + describe('with a valid api key', () => { + it('should respond repos json', (done) => { request(app) - .get('/api/repos?api-key=foo') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(/"name":"express"/) - .expect(/"url":"https:\/\/github.com\/expressjs\/express"/) - .expect(200, done) + .get('/api/repos?api-key=foo') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(/"name":"express"/) + .expect(/"url":"https:\/\/github.com\/expressjs\/express"/) + .expect(200, done) }) }) }) - describe('GET /api/user/:name/repos', function(){ - describe('without an api key', function(){ - it('should respond with 400 bad request', function(done){ + describe('GET /api/user/:name/repos', () => { + describe('without an api key', () => { + it('should respond with 400 bad request', (done) => { request(app) - .get('/api/user/loki/repos') - .expect(400, done); + .get('/api/user/loki/repos') + .expect(400, done) }) }) - describe('with an invalid api key', function(){ - it('should respond with 401 unauthorized', function(done){ + describe('with an invalid api key', () => { + it('should respond with 401 unauthorized', (done) => { request(app) - .get('/api/user/loki/repos?api-key=rawr') - .expect(401, done); + .get('/api/user/loki/repos?api-key=rawr') + .expect(401, done) }) }) - describe('with a valid api key', function(){ - it('should respond user repos json', function(done){ + describe('with a valid api key', () => { + it('should respond user repos json', (done) => { request(app) - .get('/api/user/loki/repos?api-key=foo') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(/"name":"stylus"/) - .expect(/"url":"https:\/\/github.com\/learnboost\/stylus"/) - .expect(200, done) + .get('/api/user/loki/repos?api-key=foo') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(/"name":"stylus"/) + .expect(/"url":"https:\/\/github.com\/learnboost\/stylus"/) + .expect(200, done) }) - it('should 404 with unknown user', function(done){ + it('should 404 with unknown user', (done) => { request(app) - .get('/api/user/bob/repos?api-key=foo') - .expect(404, done) + .get('/api/user/bob/repos?api-key=foo') + .expect(404, done) }) }) }) - describe('when requesting an invalid route', function(){ - it('should respond with 404 json', function(done){ + describe('when requesting an invalid route', () => { + it('should respond with 404 json', (done) => { request(app) .get('/api/something?api-key=bar') .expect('Content-Type', /json/) diff --git a/test/app.all.js b/test/app.all.js index e4afca7d731..caaa38262c5 100644 --- a/test/app.all.js +++ b/test/app.all.js @@ -1,17 +1,17 @@ 'use strict' -var after = require('after') -var express = require('../') - , request = require('supertest'); +const after = require('after') +const express = require('../') +const request = require('supertest') -describe('app.all()', function(){ - it('should add a router per method', function(done){ - var app = express(); - var cb = after(2, done) +describe('app.all()', () => { + it('should add a router per method', (done) => { + const app = express() + const cb = after(2, done) - app.all('/tobi', function(req, res){ - res.end(req.method); - }); + app.all('/tobi', (req, res) => { + res.end(req.method) + }) request(app) .put('/tobi') @@ -22,17 +22,17 @@ describe('app.all()', function(){ .expect(200, 'GET', cb) }) - it('should run the callback for a method just once', function(done){ - var app = express() - , n = 0; + it('should run the callback for a method just once', (done) => { + const app = express() + let n = 0 - app.all('/*splat', function(req, res, next){ - if (n++) return done(new Error('DELETE called several times')); - next(); - }); + app.all('/*splat', (req, res, next) => { + if (n++) return done(new Error('DELETE called several times')) + next() + }) request(app) - .del('/tobi') - .expect(404, done); + .del('/tobi') + .expect(404, done) }) }) diff --git a/test/app.engine.js b/test/app.engine.js index b0553aa247e..6927751f6e7 100644 --- a/test/app.engine.js +++ b/test/app.engine.js @@ -1,82 +1,82 @@ 'use strict' -var assert = require('node:assert') -var express = require('../') - , fs = require('node:fs'); -var path = require('node:path') +const assert = require('node:assert') +const express = require('../') +const fs = require('node:fs') +const path = require('node:path') -function render(path, options, fn) { - fs.readFile(path, 'utf8', function(err, str){ - if (err) return fn(err); - str = str.replace('{{user.name}}', options.user.name); - fn(null, str); - }); +function render (path, options, fn) { + fs.readFile(path, 'utf8', (err, str) => { + if (err) return fn(err) + str = str.replace('{{user.name}}', options.user.name) + fn(null, str) + }) } -describe('app', function(){ - describe('.engine(ext, fn)', function(){ - it('should map a template engine', function(done){ - var app = express(); +describe('app', () => { + describe('.engine(ext, fn)', () => { + it('should map a template engine', (done) => { + const app = express() app.set('views', path.join(__dirname, 'fixtures')) - app.engine('.html', render); - app.locals.user = { name: 'tobi' }; + app.engine('.html', render) + app.locals.user = { name: 'tobi' } - app.render('user.html', function(err, str){ - if (err) return done(err); + app.render('user.html', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should throw when the callback is missing', function(){ - var app = express(); - assert.throws(function () { - app.engine('.html', null); + it('should throw when the callback is missing', () => { + const app = express() + assert.throws(() => { + app.engine('.html', null) }, /callback function required/) }) - it('should work without leading "."', function(done){ - var app = express(); + it('should work without leading "."', (done) => { + const app = express() app.set('views', path.join(__dirname, 'fixtures')) - app.engine('html', render); - app.locals.user = { name: 'tobi' }; + app.engine('html', render) + app.locals.user = { name: 'tobi' } - app.render('user.html', function(err, str){ - if (err) return done(err); + app.render('user.html', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should work "view engine" setting', function(done){ - var app = express(); + it('should work "view engine" setting', (done) => { + const app = express() app.set('views', path.join(__dirname, 'fixtures')) - app.engine('html', render); - app.set('view engine', 'html'); - app.locals.user = { name: 'tobi' }; + app.engine('html', render) + app.set('view engine', 'html') + app.locals.user = { name: 'tobi' } - app.render('user', function(err, str){ - if (err) return done(err); + app.render('user', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should work "view engine" with leading "."', function(done){ - var app = express(); + it('should work "view engine" with leading "."', (done) => { + const app = express() app.set('views', path.join(__dirname, 'fixtures')) - app.engine('.html', render); - app.set('view engine', '.html'); - app.locals.user = { name: 'tobi' }; + app.engine('.html', render) + app.set('view engine', '.html') + app.locals.user = { name: 'tobi' } - app.render('user', function(err, str){ - if (err) return done(err); + app.render('user', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) }) diff --git a/test/app.head.js b/test/app.head.js index 0207caaedad..cc3f9309f2c 100644 --- a/test/app.head.js +++ b/test/app.head.js @@ -1,62 +1,62 @@ 'use strict' -var express = require('../'); -var request = require('supertest'); -var assert = require('node:assert'); +const express = require('../') +const request = require('supertest') +const assert = require('node:assert') -describe('HEAD', function(){ - it('should default to GET', function(done){ - var app = express(); +describe('HEAD', () => { + it('should default to GET', (done) => { + const app = express() - app.get('/tobi', function(req, res){ + app.get('/tobi', (req, res) => { // send() detects HEAD - res.send('tobi'); - }); + res.send('tobi') + }) request(app) - .head('/tobi') - .expect(200, done); + .head('/tobi') + .expect(200, done) }) - it('should output the same headers as GET requests', function(done){ - var app = express(); + it('should output the same headers as GET requests', (done) => { + const app = express() - app.get('/tobi', function(req, res){ + app.get('/tobi', (req, res) => { // send() detects HEAD - res.send('tobi'); - }); + res.send('tobi') + }) request(app) - .head('/tobi') - .expect(200, function(err, res){ - if (err) return done(err); - var headers = res.headers; - request(app) - .get('/tobi') - .expect(200, function(err, res){ - if (err) return done(err); - delete headers.date; - delete res.headers.date; - assert.deepEqual(res.headers, headers); - done(); - }); - }); + .head('/tobi') + .expect(200, (err, res) => { + if (err) return done(err) + const headers = res.headers + request(app) + .get('/tobi') + .expect(200, (err, res) => { + if (err) return done(err) + delete headers.date + delete res.headers.date + assert.deepEqual(res.headers, headers) + done() + }) + }) }) }) -describe('app.head()', function(){ - it('should override', function(done){ - var app = express() +describe('app.head()', () => { + it('should override', (done) => { + const app = express() - app.head('/tobi', function(req, res){ + app.head('/tobi', (req, res) => { res.header('x-method', 'head') res.end() - }); + }) - app.get('/tobi', function(req, res){ + app.get('/tobi', (req, res) => { res.header('x-method', 'get') - res.send('tobi'); - }); + res.send('tobi') + }) request(app) .head('/tobi') diff --git a/test/app.js b/test/app.js index c1e815a052d..1f0c694e265 100644 --- a/test/app.js +++ b/test/app.js @@ -1,53 +1,53 @@ 'use strict' -var assert = require('node:assert') -var express = require('..') -var request = require('supertest') - -describe('app', function(){ - it('should inherit from event emitter', function(done){ - var app = express(); - app.on('foo', done); - app.emit('foo'); +const assert = require('node:assert') +const express = require('../') +const request = require('supertest') + +describe('app', () => { + it('should inherit from event emitter', (done) => { + const app = express() + app.on('foo', done) + app.emit('foo') }) - it('should be callable', function(){ - var app = express(); - assert.equal(typeof app, 'function'); + it('should be callable', () => { + const app = express() + assert.equal(typeof app, 'function') }) - it('should 404 without routes', function(done){ + it('should 404 without routes', (done) => { request(express()) - .get('/') - .expect(404, done); + .get('/') + .expect(404, done) }) }) -describe('app.parent', function(){ - it('should return the parent when mounted', function(){ - var app = express() - , blog = express() - , blogAdmin = express(); +describe('app.parent', () => { + it('should return the parent when mounted', () => { + const app = express() + const blog = express() + const blogAdmin = express() - app.use('/blog', blog); - blog.use('/admin', blogAdmin); + app.use('/blog', blog) + blog.use('/admin', blogAdmin) - assert(!app.parent, 'app.parent'); + assert(!app.parent, 'app.parent') assert.strictEqual(blog.parent, app) assert.strictEqual(blogAdmin.parent, blog) }) }) -describe('app.mountpath', function(){ - it('should return the mounted path', function(){ - var admin = express(); - var app = express(); - var blog = express(); - var fallback = express(); +describe('app.mountpath', () => { + it('should return the mounted path', () => { + const admin = express() + const app = express() + const blog = express() + const fallback = express() - app.use('/blog', blog); - app.use(fallback); - blog.use('/admin', admin); + app.use('/blog', blog) + app.use(fallback) + blog.use('/admin', admin) assert.strictEqual(admin.mountpath, '/admin') assert.strictEqual(app.mountpath, '/') @@ -56,14 +56,14 @@ describe('app.mountpath', function(){ }) }) -describe('app.path()', function(){ - it('should return the canonical', function(){ - var app = express() - , blog = express() - , blogAdmin = express(); +describe('app.path()', () => { + it('should return the canonical', () => { + const app = express() + const blog = express() + const blogAdmin = express() - app.use('/blog', blog); - blog.use('/admin', blogAdmin); + app.use('/blog', blog) + blog.use('/admin', blogAdmin) assert.strictEqual(app.path(), '') assert.strictEqual(blog.path(), '/blog') @@ -71,7 +71,7 @@ describe('app.path()', function(){ }) }) -describe('in development', function(){ +describe('in development', () => { before(function () { this.env = process.env.NODE_ENV process.env.NODE_ENV = 'development' @@ -81,13 +81,13 @@ describe('in development', function(){ process.env.NODE_ENV = this.env }) - it('should disable "view cache"', function(){ - var app = express(); + it('should disable "view cache"', () => { + const app = express() assert.ok(!app.enabled('view cache')) }) }) -describe('in production', function(){ +describe('in production', () => { before(function () { this.env = process.env.NODE_ENV process.env.NODE_ENV = 'production' @@ -97,13 +97,13 @@ describe('in production', function(){ process.env.NODE_ENV = this.env }) - it('should enable "view cache"', function(){ - var app = express(); + it('should enable "view cache"', () => { + const app = express() assert.ok(app.enabled('view cache')) }) }) -describe('without NODE_ENV', function(){ +describe('without NODE_ENV', () => { before(function () { this.env = process.env.NODE_ENV process.env.NODE_ENV = '' @@ -113,8 +113,8 @@ describe('without NODE_ENV', function(){ process.env.NODE_ENV = this.env }) - it('should default to development', function(){ - var app = express(); + it('should default to development', () => { + const app = express() assert.strictEqual(app.get('env'), 'development') }) }) diff --git a/test/app.listen.js b/test/app.listen.js index 3ef94ff184a..a0481edc65f 100644 --- a/test/app.listen.js +++ b/test/app.listen.js @@ -1,55 +1,55 @@ 'use strict' -var express = require('../') -var assert = require('node:assert') +const express = require('../') +const assert = require('node:assert') -describe('app.listen()', function(){ - it('should wrap with an HTTP server', function(done){ - var app = express(); +describe('app.listen()', () => { + it('should wrap with an HTTP server', (done) => { + const app = express() - var server = app.listen(0, function () { + const server = app.listen(0, () => { server.close(done) - }); + }) }) - it('should callback on HTTP server errors', function (done) { - var app1 = express() - var app2 = express() + it('should callback on HTTP server errors', (done) => { + const app1 = express() + const app2 = express() - var server1 = app1.listen(0, function (err) { + const server1 = app1.listen(0, (err) => { assert(!err) - app2.listen(server1.address().port, function (err) { + app2.listen(server1.address().port, (err) => { assert(err.code === 'EADDRINUSE') server1.close() done() }) }) }) - it('accepts port + hostname + backlog + callback', function (done) { - const app = express(); - const server = app.listen(0, '127.0.0.1', 5, function () { - const { address, port } = server.address(); - assert.strictEqual(address, '127.0.0.1'); - assert(Number.isInteger(port) && port > 0); + it('accepts port + hostname + backlog + callback', (done) => { + const app = express() + const server = app.listen(0, '127.0.0.1', 5, () => { + const { address, port } = server.address() + assert.strictEqual(address, '127.0.0.1') + assert(Number.isInteger(port) && port > 0) // backlog isn’t directly inspectable, but if no error was thrown // we know it was accepted. - server.close(done); - }); - }); - it('accepts just a callback (no args)', function (done) { - const app = express(); + server.close(done) + }) + }) + it('accepts just a callback (no args)', (done) => { + const app = express() // same as app.listen(0, done) - const server = app.listen(); - server.close(done); - }); - it('server.address() gives a { address, port, family } object', function (done) { - const app = express(); + const server = app.listen() + server.close(done) + }) + it('server.address() gives a { address, port, family } object', (done) => { + const app = express() const server = app.listen(0, () => { - const addr = server.address(); - assert(addr && typeof addr === 'object'); - assert.strictEqual(typeof addr.address, 'string'); - assert(Number.isInteger(addr.port) && addr.port > 0); - assert(typeof addr.family === 'string'); - server.close(done); - }); - }); + const addr = server.address() + assert(addr && typeof addr === 'object') + assert.strictEqual(typeof addr.address, 'string') + assert(Number.isInteger(addr.port) && addr.port > 0) + assert(typeof addr.family === 'string') + server.close(done) + }) + }) }) diff --git a/test/app.locals.js b/test/app.locals.js index 3963762fe2b..5a848e9fc18 100644 --- a/test/app.locals.js +++ b/test/app.locals.js @@ -1,20 +1,20 @@ 'use strict' -var assert = require('node:assert') -var express = require('../') +const assert = require('node:assert') +const express = require('../') -describe('app', function(){ - describe('.locals', function () { - it('should default object with null prototype', function () { - var app = express() +describe('app', () => { + describe('.locals', () => { + it('should default object with null prototype', () => { + const app = express() assert.ok(app.locals) assert.strictEqual(typeof app.locals, 'object') assert.strictEqual(Object.getPrototypeOf(app.locals), null) }) - describe('.settings', function () { - it('should contain app settings ', function () { - var app = express() + describe('.settings', () => { + it('should contain app settings ', () => { + const app = express() app.set('title', 'Express') assert.ok(app.locals.settings) assert.strictEqual(typeof app.locals.settings, 'object') diff --git a/test/app.options.js b/test/app.options.js index ee4c81631cb..9f3d8a73f9e 100644 --- a/test/app.options.js +++ b/test/app.options.js @@ -1,116 +1,116 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('OPTIONS', function(){ - it('should default to the routes defined', function(done){ - var app = express(); +describe('OPTIONS', () => { + it('should default to the routes defined', (done) => { + const app = express() - app.post('/', function(){}); - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); + app.post('/', () => {}) + app.get('/users', (req, res) => {}) + app.put('/users', (req, res) => {}) request(app) - .options('/users') - .expect('Allow', 'GET, HEAD, PUT') - .expect(200, 'GET, HEAD, PUT', done); + .options('/users') + .expect('Allow', 'GET, HEAD, PUT') + .expect(200, 'GET, HEAD, PUT', done) }) - it('should only include each method once', function(done){ - var app = express(); + it('should only include each method once', (done) => { + const app = express() - app.delete('/', function(){}); - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); - app.get('/users', function(req, res){}); + app.delete('/', () => {}) + app.get('/users', (req, res) => {}) + app.put('/users', (req, res) => {}) + app.get('/users', (req, res) => {}) request(app) - .options('/users') - .expect('Allow', 'GET, HEAD, PUT') - .expect(200, 'GET, HEAD, PUT', done); + .options('/users') + .expect('Allow', 'GET, HEAD, PUT') + .expect(200, 'GET, HEAD, PUT', done) }) - it('should not be affected by app.all', function(done){ - var app = express(); + it('should not be affected by app.all', (done) => { + const app = express() - app.get('/', function(){}); - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); - app.all('/users', function(req, res, next){ - res.setHeader('x-hit', '1'); - next(); - }); + app.get('/', () => {}) + app.get('/users', (req, res) => {}) + app.put('/users', (req, res) => {}) + app.all('/users', (req, res, next) => { + res.setHeader('x-hit', '1') + next() + }) request(app) - .options('/users') - .expect('x-hit', '1') - .expect('Allow', 'GET, HEAD, PUT') - .expect(200, 'GET, HEAD, PUT', done); + .options('/users') + .expect('x-hit', '1') + .expect('Allow', 'GET, HEAD, PUT') + .expect(200, 'GET, HEAD, PUT', done) }) - it('should not respond if the path is not defined', function(done){ - var app = express(); + it('should not respond if the path is not defined', (done) => { + const app = express() - app.get('/users', function(req, res){}); + app.get('/users', (req, res) => {}) request(app) - .options('/other') - .expect(404, done); + .options('/other') + .expect(404, done) }) - it('should forward requests down the middleware chain', function(done){ - var app = express(); - var router = new express.Router(); + it('should forward requests down the middleware chain', (done) => { + const app = express() + const router = new express.Router() - router.get('/users', function(req, res){}); - app.use(router); - app.get('/other', function(req, res){}); + router.get('/users', (req, res) => {}) + app.use(router) + app.get('/other', (req, res) => {}) request(app) - .options('/other') - .expect('Allow', 'GET, HEAD') - .expect(200, 'GET, HEAD', done); + .options('/other') + .expect('Allow', 'GET, HEAD') + .expect(200, 'GET, HEAD', done) }) - describe('when error occurs in response handler', function () { - it('should pass error to callback', function (done) { - var app = express(); - var router = express.Router(); + describe('when error occurs in response handler', () => { + it('should pass error to callback', (done) => { + const app = express() + const router = express.Router() - router.get('/users', function(req, res){}); + router.get('/users', (req, res) => {}) - app.use(function (req, res, next) { - res.writeHead(200); - next(); - }); - app.use(router); - app.use(function (err, req, res, next) { - res.end('true'); - }); + app.use((req, res, next) => { + res.writeHead(200) + next() + }) + app.use(router) + app.use((err, req, res, next) => { + res.end('true') + }) request(app) - .options('/users') - .expect(200, 'true', done) + .options('/users') + .expect(200, 'true', done) }) }) }) -describe('app.options()', function(){ - it('should override the default behavior', function(done){ - var app = express(); +describe('app.options()', () => { + it('should override the default behavior', (done) => { + const app = express() - app.options('/users', function(req, res){ - res.set('Allow', 'GET'); - res.send('GET'); - }); + app.options('/users', (req, res) => { + res.set('Allow', 'GET') + res.send('GET') + }) - app.get('/users', function(req, res){}); - app.put('/users', function(req, res){}); + app.get('/users', (req, res) => {}) + app.put('/users', (req, res) => {}) request(app) - .options('/users') - .expect('GET') - .expect('Allow', 'GET', done); + .options('/users') + .expect('GET') + .expect('Allow', 'GET', done) }) }) diff --git a/test/app.param.js b/test/app.param.js index 5c9a5630870..602bb33f737 100644 --- a/test/app.param.js +++ b/test/app.param.js @@ -1,33 +1,33 @@ 'use strict' -var express = require('../') - , request = require('supertest'); - -describe('app', function(){ - describe('.param(names, fn)', function(){ - it('should map the array', function(done){ - var app = express(); - - app.param(['id', 'uid'], function(req, res, next, id){ - id = Number(id); - if (isNaN(id)) return next('route'); - req.params.id = id; - next(); - }); - - app.get('/post/:id', function(req, res){ - var id = req.params.id; +const express = require('../') +const request = require('supertest') + +describe('app', () => { + describe('.param(names, fn)', () => { + it('should map the array', (done) => { + const app = express() + + app.param(['id', 'uid'], (req, res, next, id) => { + id = Number(id) + if (isNaN(id)) return next('route') + req.params.id = id + next() + }) + + app.get('/post/:id', (req, res) => { + const id = req.params.id res.send((typeof id) + ':' + id) - }); + }) - app.get('/user/:uid', function(req, res){ - var id = req.params.id; + app.get('/user/:uid', (req, res) => { + const id = req.params.id res.send((typeof id) + ':' + id) - }); + }) request(app) .get('/user/123') - .expect(200, 'number:123', function (err) { + .expect(200, 'number:123', (err) => { if (err) return done(err) request(app) .get('/post/123') @@ -36,288 +36,288 @@ describe('app', function(){ }) }) - describe('.param(name, fn)', function(){ - it('should map logic for a single param', function(done){ - var app = express(); + describe('.param(name, fn)', () => { + it('should map logic for a single param', (done) => { + const app = express() - app.param('id', function(req, res, next, id){ - id = Number(id); - if (isNaN(id)) return next('route'); - req.params.id = id; - next(); - }); + app.param('id', (req, res, next, id) => { + id = Number(id) + if (isNaN(id)) return next('route') + req.params.id = id + next() + }) - app.get('/user/:id', function(req, res){ - var id = req.params.id; + app.get('/user/:id', (req, res) => { + const id = req.params.id res.send((typeof id) + ':' + id) - }); + }) request(app) .get('/user/123') .expect(200, 'number:123', done) }) - it('should only call once per request', function(done) { - var app = express(); - var called = 0; - var count = 0; - - app.param('user', function(req, res, next, user) { - called++; - req.user = user; - next(); - }); - - app.get('/foo/:user', function(req, res, next) { - count++; - next(); - }); - app.get('/foo/:user', function(req, res, next) { - count++; - next(); - }); - app.use(function(req, res) { - res.end([count, called, req.user].join(' ')); - }); + it('should only call once per request', (done) => { + const app = express() + let called = 0 + let count = 0 + + app.param('user', (req, res, next, user) => { + called++ + req.user = user + next() + }) + + app.get('/foo/:user', (req, res, next) => { + count++ + next() + }) + app.get('/foo/:user', (req, res, next) => { + count++ + next() + }) + app.use((req, res) => { + res.end([count, called, req.user].join(' ')) + }) request(app) - .get('/foo/bob') - .expect('2 1 bob', done); + .get('/foo/bob') + .expect('2 1 bob', done) }) - it('should call when values differ', function(done) { - var app = express(); - var called = 0; - var count = 0; - - app.param('user', function(req, res, next, user) { - called++; - req.users = (req.users || []).concat(user); - next(); - }); - - app.get('/:user/bob', function(req, res, next) { - count++; - next(); - }); - app.get('/foo/:user', function(req, res, next) { - count++; - next(); - }); - app.use(function(req, res) { - res.end([count, called, req.users.join(',')].join(' ')); - }); + it('should call when values differ', (done) => { + const app = express() + let called = 0 + let count = 0 + + app.param('user', (req, res, next, user) => { + called++ + req.users = (req.users || []).concat(user) + next() + }) + + app.get('/:user/bob', (req, res, next) => { + count++ + next() + }) + app.get('/foo/:user', (req, res, next) => { + count++ + next() + }) + app.use((req, res) => { + res.end([count, called, req.users.join(',')].join(' ')) + }) request(app) - .get('/foo/bob') - .expect('2 2 foo,bob', done); + .get('/foo/bob') + .expect('2 2 foo,bob', done) }) - it('should support altering req.params across routes', function(done) { - var app = express(); + it('should support altering req.params across routes', (done) => { + const app = express() - app.param('user', function(req, res, next, user) { - req.params.user = 'loki'; - next(); - }); + app.param('user', (req, res, next, user) => { + req.params.user = 'loki' + next() + }) - app.get('/:user', function(req, res, next) { - next('route'); - }); - app.get('/:user', function (req, res) { - res.send(req.params.user); - }); + app.get('/:user', (req, res, next) => { + next('route') + }) + app.get('/:user', (req, res) => { + res.send(req.params.user) + }) request(app) - .get('/bob') - .expect('loki', done); + .get('/bob') + .expect('loki', done) }) - it('should not invoke without route handler', function(done) { - var app = express(); + it('should not invoke without route handler', (done) => { + const app = express() - app.param('thing', function(req, res, next, thing) { - req.thing = thing; - next(); - }); + app.param('thing', (req, res, next, thing) => { + req.thing = thing + next() + }) - app.param('user', function(req, res, next, user) { + app.param('user', (req, res, next, user) => { next(new Error('invalid invocation')) - }); + }) - app.post('/:user', function (req, res) { - res.send(req.params.user); - }); + app.post('/:user', (req, res) => { + res.send(req.params.user) + }) - app.get('/:thing', function (req, res) { - res.send(req.thing); - }); + app.get('/:thing', (req, res) => { + res.send(req.thing) + }) request(app) - .get('/bob') - .expect(200, 'bob', done); + .get('/bob') + .expect(200, 'bob', done) }) - it('should work with encoded values', function(done){ - var app = express(); + it('should work with encoded values', (done) => { + const app = express() - app.param('name', function(req, res, next, name){ - req.params.name = name; - next(); - }); + app.param('name', (req, res, next, name) => { + req.params.name = name + next() + }) - app.get('/user/:name', function(req, res){ - var name = req.params.name; - res.send('' + name); - }); + app.get('/user/:name', (req, res) => { + const name = req.params.name + res.send('' + name) + }) request(app) - .get('/user/foo%25bar') - .expect('foo%bar', done); + .get('/user/foo%25bar') + .expect('foo%bar', done) }) - it('should catch thrown error', function(done){ - var app = express(); + it('should catch thrown error', (done) => { + const app = express() - app.param('id', function(req, res, next, id){ - throw new Error('err!'); - }); + app.param('id', (req, res, next, id) => { + throw new Error('err!') + }) - app.get('/user/:id', function(req, res){ - var id = req.params.id; - res.send('' + id); - }); + app.get('/user/:id', (req, res) => { + const id = req.params.id + res.send('' + id) + }) request(app) - .get('/user/123') - .expect(500, done); + .get('/user/123') + .expect(500, done) }) - it('should catch thrown secondary error', function(done){ - var app = express(); + it('should catch thrown secondary error', (done) => { + const app = express() - app.param('id', function(req, res, next, val){ - process.nextTick(next); - }); + app.param('id', (req, res, next, val) => { + process.nextTick(next) + }) - app.param('id', function(req, res, next, id){ - throw new Error('err!'); - }); + app.param('id', (req, res, next, id) => { + throw new Error('err!') + }) - app.get('/user/:id', function(req, res){ - var id = req.params.id; - res.send('' + id); - }); + app.get('/user/:id', (req, res) => { + const id = req.params.id + res.send('' + id) + }) request(app) - .get('/user/123') - .expect(500, done); + .get('/user/123') + .expect(500, done) }) - it('should defer to next route', function(done){ - var app = express(); + it('should defer to next route', (done) => { + const app = express() - app.param('id', function(req, res, next, id){ - next('route'); - }); + app.param('id', (req, res, next, id) => { + next('route') + }) - app.get('/user/:id', function(req, res){ - var id = req.params.id; - res.send('' + id); - }); + app.get('/user/:id', (req, res) => { + const id = req.params.id + res.send('' + id) + }) - app.get('/:name/123', function(req, res){ - res.send('name'); - }); + app.get('/:name/123', (req, res) => { + res.send('name') + }) request(app) - .get('/user/123') - .expect('name', done); + .get('/user/123') + .expect('name', done) }) - it('should defer all the param routes', function(done){ - var app = express(); + it('should defer all the param routes', (done) => { + const app = express() - app.param('id', function(req, res, next, val){ - if (val === 'new') return next('route'); - return next(); - }); + app.param('id', (req, res, next, val) => { + if (val === 'new') return next('route') + return next() + }) - app.all('/user/:id', function(req, res){ - res.send('all.id'); - }); + app.all('/user/:id', (req, res) => { + res.send('all.id') + }) - app.get('/user/:id', function(req, res){ - res.send('get.id'); - }); + app.get('/user/:id', (req, res) => { + res.send('get.id') + }) - app.get('/user/new', function(req, res){ - res.send('get.new'); - }); + app.get('/user/new', (req, res) => { + res.send('get.new') + }) request(app) - .get('/user/new') - .expect('get.new', done); + .get('/user/new') + .expect('get.new', done) }) - it('should not call when values differ on error', function(done) { - var app = express(); - var called = 0; - var count = 0; - - app.param('user', function(req, res, next, user) { - called++; - if (user === 'foo') throw new Error('err!'); - req.user = user; - next(); - }); - - app.get('/:user/bob', function(req, res, next) { - count++; - next(); - }); - app.get('/foo/:user', function(req, res, next) { - count++; - next(); - }); - - app.use(function(err, req, res, next) { - res.status(500); - res.send([count, called, err.message].join(' ')); - }); + it('should not call when values differ on error', (done) => { + const app = express() + let called = 0 + let count = 0 + + app.param('user', (req, res, next, user) => { + called++ + if (user === 'foo') throw new Error('err!') + req.user = user + next() + }) + + app.get('/:user/bob', (req, res, next) => { + count++ + next() + }) + app.get('/foo/:user', (req, res, next) => { + count++ + next() + }) + + app.use((err, req, res, next) => { + res.status(500) + res.send([count, called, err.message].join(' ')) + }) request(app) - .get('/foo/bob') - .expect(500, '0 1 err!', done) - }); - - it('should call when values differ when using "next"', function(done) { - var app = express(); - var called = 0; - var count = 0; - - app.param('user', function(req, res, next, user) { - called++; - if (user === 'foo') return next('route'); - req.user = user; - next(); - }); - - app.get('/:user/bob', function(req, res, next) { - count++; - next(); - }); - app.get('/foo/:user', function(req, res, next) { - count++; - next(); - }); - app.use(function(req, res) { - res.end([count, called, req.user].join(' ')); - }); + .get('/foo/bob') + .expect(500, '0 1 err!', done) + }) + + it('should call when values differ when using "next"', (done) => { + const app = express() + let called = 0 + let count = 0 + + app.param('user', (req, res, next, user) => { + called++ + if (user === 'foo') return next('route') + req.user = user + next() + }) + + app.get('/:user/bob', (req, res, next) => { + count++ + next() + }) + app.get('/foo/:user', (req, res, next) => { + count++ + next() + }) + app.use((req, res) => { + res.end([count, called, req.user].join(' ')) + }) request(app) - .get('/foo/bob') - .expect('1 2 bob', done); + .get('/foo/bob') + .expect('1 2 bob', done) }) }) }) diff --git a/test/app.render.js b/test/app.render.js index ca15e761d35..8d1a804e2c6 100644 --- a/test/app.render.js +++ b/test/app.render.js @@ -1,104 +1,104 @@ 'use strict' -var assert = require('node:assert') -var express = require('..'); -var path = require('node:path') -var tmpl = require('./support/tmpl'); +const assert = require('node:assert') +const express = require('../') +const path = require('node:path') +const tmpl = require('./support/tmpl') -describe('app', function(){ - describe('.render(name, fn)', function(){ - it('should support absolute paths', function(done){ - var app = createApp(); +describe('app', () => { + describe('.render(name, fn)', () => { + it('should support absolute paths', (done) => { + const app = createApp() - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.render(path.join(__dirname, 'fixtures', 'user.tmpl'), function (err, str) { - if (err) return done(err); + app.render(path.join(__dirname, 'fixtures', 'user.tmpl'), (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should support absolute paths with "view engine"', function(done){ - var app = createApp(); + it('should support absolute paths with "view engine"', (done) => { + const app = createApp() - app.set('view engine', 'tmpl'); - app.locals.user = { name: 'tobi' }; + app.set('view engine', 'tmpl') + app.locals.user = { name: 'tobi' } - app.render(path.join(__dirname, 'fixtures', 'user'), function (err, str) { - if (err) return done(err); + app.render(path.join(__dirname, 'fixtures', 'user'), (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should expose app.locals', function(done){ - var app = createApp(); + it('should expose app.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.render('user.tmpl', function (err, str) { - if (err) return done(err); + app.render('user.tmpl', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should support index.', function(done){ - var app = createApp(); + it('should support index.', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.set('view engine', 'tmpl'); + app.set('view engine', 'tmpl') - app.render('blog/post', function (err, str) { - if (err) return done(err); + app.render('blog/post', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        blog post

        ') - done(); + done() }) }) - it('should handle render error throws', function(done){ - var app = express(); + it('should handle render error throws', (done) => { + const app = express() - function View(name, options){ - this.name = name; - this.path = 'fale'; + function View (name, options) { + this.name = name + this.path = 'fale' } - View.prototype.render = function(options, fn){ - throw new Error('err!'); - }; + View.prototype.render = function (options, fn) { + throw new Error('err!') + } - app.set('view', View); + app.set('view', View) - app.render('something', function(err, str){ + app.render('something', (err, str) => { assert.ok(err) assert.strictEqual(err.message, 'err!') - done(); + done() }) }) - describe('when the file does not exist', function(){ - it('should provide a helpful error', function(done){ - var app = createApp(); + describe('when the file does not exist', () => { + it('should provide a helpful error', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.render('rawr.tmpl', function (err) { + app.render('rawr.tmpl', (err) => { assert.ok(err) assert.equal(err.message, 'Failed to lookup view "rawr.tmpl" in views directory "' + path.join(__dirname, 'fixtures') + '"') - done(); - }); + done() + }) }) }) - describe('when an error occurs', function(){ - it('should invoke the callback', function(done){ - var app = createApp(); + describe('when an error occurs', () => { + it('should invoke the callback', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.render('user.tmpl', function (err) { + app.render('user.tmpl', (err) => { assert.ok(err) assert.equal(err.name, 'RenderError') done() @@ -106,258 +106,258 @@ describe('app', function(){ }) }) - describe('when an extension is given', function(){ - it('should render the template', function(done){ - var app = createApp(); + describe('when an extension is given', () => { + it('should render the template', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.render('email.tmpl', function (err, str) { - if (err) return done(err); + app.render('email.tmpl', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        This is an email

        ') - done(); + done() }) }) }) - describe('when "view engine" is given', function(){ - it('should render the template', function(done){ - var app = createApp(); + describe('when "view engine" is given', () => { + it('should render the template', (done) => { + const app = createApp() - app.set('view engine', 'tmpl'); + app.set('view engine', 'tmpl') app.set('views', path.join(__dirname, 'fixtures')) - app.render('email', function(err, str){ - if (err) return done(err); + app.render('email', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        This is an email

        ') - done(); + done() }) }) }) - describe('when "views" is given', function(){ - it('should lookup the file in the path', function(done){ - var app = createApp(); + describe('when "views" is given', () => { + it('should lookup the file in the path', (done) => { + const app = createApp() - app.set('views', path.join(__dirname, 'fixtures', 'default_layout')) - app.locals.user = { name: 'tobi' }; + app.set('views', path.join(__dirname, 'fixtures', 'default_layout')) + app.locals.user = { name: 'tobi' } - app.render('user.tmpl', function (err, str) { - if (err) return done(err); + app.render('user.tmpl', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - describe('when array of paths', function(){ - it('should lookup the file in the path', function(done){ - var app = createApp(); - var views = [ + describe('when array of paths', () => { + it('should lookup the file in the path', (done) => { + const app = createApp() + const views = [ path.join(__dirname, 'fixtures', 'local_layout'), path.join(__dirname, 'fixtures', 'default_layout') ] - app.set('views', views); - app.locals.user = { name: 'tobi' }; + app.set('views', views) + app.locals.user = { name: 'tobi' } - app.render('user.tmpl', function (err, str) { - if (err) return done(err); + app.render('user.tmpl', (err, str) => { + if (err) return done(err) assert.strictEqual(str, 'tobi') - done(); + done() }) }) - it('should lookup in later paths until found', function(done){ - var app = createApp(); - var views = [ + it('should lookup in later paths until found', (done) => { + const app = createApp() + const views = [ path.join(__dirname, 'fixtures', 'local_layout'), path.join(__dirname, 'fixtures', 'default_layout') ] - app.set('views', views); - app.locals.name = 'tobi'; + app.set('views', views) + app.locals.name = 'tobi' - app.render('name.tmpl', function (err, str) { - if (err) return done(err); + app.render('name.tmpl', (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should error if file does not exist', function(done){ - var app = createApp(); - var views = [ + it('should error if file does not exist', (done) => { + const app = createApp() + const views = [ path.join(__dirname, 'fixtures', 'local_layout'), path.join(__dirname, 'fixtures', 'default_layout') ] - app.set('views', views); - app.locals.name = 'tobi'; + app.set('views', views) + app.locals.name = 'tobi' - app.render('pet.tmpl', function (err, str) { + app.render('pet.tmpl', (err, str) => { assert.ok(err) assert.equal(err.message, 'Failed to lookup view "pet.tmpl" in views directories "' + views[0] + '" or "' + views[1] + '"') - done(); + done() }) }) }) }) - describe('when a "view" constructor is given', function(){ - it('should create an instance of it', function(done){ - var app = express(); + describe('when a "view" constructor is given', () => { + it('should create an instance of it', (done) => { + const app = express() - function View(name, options){ - this.name = name; - this.path = 'path is required by application.js as a signal of success even though it is not used there.'; + function View (name, options) { + this.name = name + this.path = 'path is required by application.js as a signal of success even though it is not used there.' } - View.prototype.render = function(options, fn){ - fn(null, 'abstract engine'); - }; + View.prototype.render = function (options, fn) { + fn(null, 'abstract engine') + } - app.set('view', View); + app.set('view', View) - app.render('something', function(err, str){ - if (err) return done(err); + app.render('something', (err, str) => { + if (err) return done(err) assert.strictEqual(str, 'abstract engine') - done(); + done() }) }) }) - describe('caching', function(){ - it('should always lookup view without cache', function(done){ - var app = express(); - var count = 0; + describe('caching', () => { + it('should always lookup view without cache', (done) => { + const app = express() + let count = 0 - function View(name, options){ - this.name = name; - this.path = 'fake'; - count++; + function View (name, options) { + this.name = name + this.path = 'fake' + count++ } - View.prototype.render = function(options, fn){ - fn(null, 'abstract engine'); - }; + View.prototype.render = function (options, fn) { + fn(null, 'abstract engine') + } - app.set('view cache', false); - app.set('view', View); + app.set('view cache', false) + app.set('view', View) - app.render('something', function(err, str){ - if (err) return done(err); + app.render('something', (err, str) => { + if (err) return done(err) assert.strictEqual(count, 1) assert.strictEqual(str, 'abstract engine') - app.render('something', function(err, str){ - if (err) return done(err); + app.render('something', (err, str) => { + if (err) return done(err) assert.strictEqual(count, 2) assert.strictEqual(str, 'abstract engine') - done(); + done() }) }) }) - it('should cache with "view cache" setting', function(done){ - var app = express(); - var count = 0; + it('should cache with "view cache" setting', (done) => { + const app = express() + let count = 0 - function View(name, options){ - this.name = name; - this.path = 'fake'; - count++; + function View (name, options) { + this.name = name + this.path = 'fake' + count++ } - View.prototype.render = function(options, fn){ - fn(null, 'abstract engine'); - }; + View.prototype.render = function (options, fn) { + fn(null, 'abstract engine') + } - app.set('view cache', true); - app.set('view', View); + app.set('view cache', true) + app.set('view', View) - app.render('something', function(err, str){ - if (err) return done(err); + app.render('something', (err, str) => { + if (err) return done(err) assert.strictEqual(count, 1) assert.strictEqual(str, 'abstract engine') - app.render('something', function(err, str){ - if (err) return done(err); + app.render('something', (err, str) => { + if (err) return done(err) assert.strictEqual(count, 1) assert.strictEqual(str, 'abstract engine') - done(); + done() }) }) }) }) }) - describe('.render(name, options, fn)', function(){ - it('should render the template', function(done){ - var app = createApp(); + describe('.render(name, options, fn)', () => { + it('should render the template', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - var user = { name: 'tobi' }; + const user = { name: 'tobi' } - app.render('user.tmpl', { user: user }, function (err, str) { - if (err) return done(err); + app.render('user.tmpl', { user }, (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should expose app.locals', function(done){ - var app = createApp(); + it('should expose app.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.render('user.tmpl', {}, function (err, str) { - if (err) return done(err); + app.render('user.tmpl', {}, (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        tobi

        ') - done(); + done() }) }) - it('should give precedence to app.render() locals', function(done){ - var app = createApp(); + it('should give precedence to app.render() locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.user = { name: 'tobi' }; - var jane = { name: 'jane' }; + app.locals.user = { name: 'tobi' } + const jane = { name: 'jane' } - app.render('user.tmpl', { user: jane }, function (err, str) { - if (err) return done(err); + app.render('user.tmpl', { user: jane }, (err, str) => { + if (err) return done(err) assert.strictEqual(str, '

        jane

        ') - done(); + done() }) }) - describe('caching', function(){ - it('should cache with cache option', function(done){ - var app = express(); - var count = 0; + describe('caching', () => { + it('should cache with cache option', (done) => { + const app = express() + let count = 0 - function View(name, options){ - this.name = name; - this.path = 'fake'; - count++; + function View (name, options) { + this.name = name + this.path = 'fake' + count++ } - View.prototype.render = function(options, fn){ - fn(null, 'abstract engine'); - }; + View.prototype.render = function (options, fn) { + fn(null, 'abstract engine') + } - app.set('view cache', false); - app.set('view', View); + app.set('view cache', false) + app.set('view', View) - app.render('something', {cache: true}, function(err, str){ - if (err) return done(err); + app.render('something', { cache: true }, (err, str) => { + if (err) return done(err) assert.strictEqual(count, 1) assert.strictEqual(str, 'abstract engine') - app.render('something', {cache: true}, function(err, str){ - if (err) return done(err); + app.render('something', { cache: true }, (err, str) => { + if (err) return done(err) assert.strictEqual(count, 1) assert.strictEqual(str, 'abstract engine') - done(); + done() }) }) }) @@ -365,10 +365,10 @@ describe('app', function(){ }) }) -function createApp() { - var app = express(); +function createApp () { + const app = express() - app.engine('.tmpl', tmpl); + app.engine('.tmpl', tmpl) - return app; + return app } diff --git a/test/app.request.js b/test/app.request.js index b6c00f5baa3..71cd862105e 100644 --- a/test/app.request.js +++ b/test/app.request.js @@ -1,41 +1,41 @@ 'use strict' -var after = require('after') -var express = require('../') - , request = require('supertest'); +const after = require('after') +const express = require('../') +const request = require('supertest') -describe('app', function(){ - describe('.request', function(){ - it('should extend the request prototype', function(done){ - var app = express(); +describe('app', () => { + describe('.request', () => { + it('should extend the request prototype', (done) => { + const app = express() - app.request.querystring = function(){ - return require('node:url').parse(this.url).query; - }; + app.request.querystring = function () { + return (new URL(this.url)).query + } - app.use(function(req, res){ - res.end(req.querystring()); - }); + app.use((req, res) => { + res.end(req.querystring()) + }) request(app) - .get('/foo?name=tobi') - .expect('name=tobi', done); + .get('/foo?name=tobi') + .expect('name=tobi', done) }) - it('should only extend for the referenced app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should only extend for the referenced app', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.request.foobar = function () { return 'tobi' } - app1.get('/', function (req, res) { + app1.get('/', (req, res) => { res.send(req.foobar()) }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.send(req.foobar()) }) @@ -48,10 +48,10 @@ describe('app', function(){ .expect(500, /(?:not a function|has no method)/, cb) }) - it('should inherit to sub apps', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should inherit to sub apps', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.request.foobar = function () { return 'tobi' @@ -59,11 +59,11 @@ describe('app', function(){ app1.use('/sub', app2) - app1.get('/', function (req, res) { + app1.get('/', (req, res) => { res.send(req.foobar()) }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.send(req.foobar()) }) @@ -76,10 +76,10 @@ describe('app', function(){ .expect(200, 'tobi', cb) }) - it('should allow sub app to override', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should allow sub app to override', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.request.foobar = function () { return 'tobi' @@ -91,11 +91,11 @@ describe('app', function(){ app1.use('/sub', app2) - app1.get('/', function (req, res) { + app1.get('/', (req, res) => { res.send(req.foobar()) }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.send(req.foobar()) }) @@ -108,10 +108,10 @@ describe('app', function(){ .expect(200, 'loki', cb) }) - it('should not pollute parent app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should not pollute parent app', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.request.foobar = function () { return 'tobi' @@ -123,11 +123,11 @@ describe('app', function(){ app1.use('/sub', app2) - app1.get('/sub/foo', function (req, res) { + app1.get('/sub/foo', (req, res) => { res.send(req.foobar()) }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.send(req.foobar()) }) diff --git a/test/app.response.js b/test/app.response.js index 5fb69f6275a..98cb40339eb 100644 --- a/test/app.response.js +++ b/test/app.response.js @@ -1,41 +1,41 @@ 'use strict' -var after = require('after') -var express = require('../') - , request = require('supertest'); +const after = require('after') +const express = require('../') +const request = require('supertest') -describe('app', function(){ - describe('.response', function(){ - it('should extend the response prototype', function(done){ - var app = express(); +describe('app', () => { + describe('.response', () => { + it('should extend the response prototype', (done) => { + const app = express() - app.response.shout = function(str){ - this.send(str.toUpperCase()); - }; + app.response.shout = function (str) { + this.send(str.toUpperCase()) + } - app.use(function(req, res){ - res.shout('hey'); - }); + app.use((req, res) => { + res.shout('hey') + }) request(app) - .get('/') - .expect('HEY', done); + .get('/') + .expect('HEY', done) }) - it('should only extend for the referenced app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should only extend for the referenced app', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.response.shout = function (str) { this.send(str.toUpperCase()) } - app1.get('/', function (req, res) { + app1.get('/', (req, res) => { res.shout('foo') }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.shout('foo') }) @@ -48,10 +48,10 @@ describe('app', function(){ .expect(500, /(?:not a function|has no method)/, cb) }) - it('should inherit to sub apps', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should inherit to sub apps', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.response.shout = function (str) { this.send(str.toUpperCase()) @@ -59,11 +59,11 @@ describe('app', function(){ app1.use('/sub', app2) - app1.get('/', function (req, res) { + app1.get('/', (req, res) => { res.shout('foo') }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.shout('foo') }) @@ -76,10 +76,10 @@ describe('app', function(){ .expect(200, 'FOO', cb) }) - it('should allow sub app to override', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should allow sub app to override', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.response.shout = function (str) { this.send(str.toUpperCase()) @@ -91,11 +91,11 @@ describe('app', function(){ app1.use('/sub', app2) - app1.get('/', function (req, res) { + app1.get('/', (req, res) => { res.shout('foo') }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.shout('foo') }) @@ -108,10 +108,10 @@ describe('app', function(){ .expect(200, 'foo!', cb) }) - it('should not pollute parent app', function (done) { - var app1 = express() - var app2 = express() - var cb = after(2, done) + it('should not pollute parent app', (done) => { + const app1 = express() + const app2 = express() + const cb = after(2, done) app1.response.shout = function (str) { this.send(str.toUpperCase()) @@ -123,11 +123,11 @@ describe('app', function(){ app1.use('/sub', app2) - app1.get('/sub/foo', function (req, res) { + app1.get('/sub/foo', (req, res) => { res.shout('foo') }) - app2.get('/', function (req, res) { + app2.get('/', (req, res) => { res.shout('foo') }) diff --git a/test/app.route.js b/test/app.route.js index 03ae1293685..71d8a82d7b5 100644 --- a/test/app.route.js +++ b/test/app.route.js @@ -1,197 +1,189 @@ 'use strict' -var express = require('../'); -var request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('app.route', function(){ - it('should return a new route', function(done){ - var app = express(); +describe('app.route', () => { + it('should return a new route', (done) => { + const app = express() app.route('/foo') - .get(function(req, res) { - res.send('get'); - }) - .post(function(req, res) { - res.send('post'); - }); + .get((req, res) => { + res.send('get') + }) + .post((req, res) => { + res.send('post') + }) request(app) - .post('/foo') - .expect('post', done); - }); + .post('/foo') + .expect('post', done) + }) - it('should all .VERB after .all', function(done){ - var app = express(); + it('should all .VERB after .all', (done) => { + const app = express() app.route('/foo') - .all(function(req, res, next) { - next(); - }) - .get(function(req, res) { - res.send('get'); - }) - .post(function(req, res) { - res.send('post'); - }); + .all((req, res, next) => { + next() + }) + .get((req, res) => { + res.send('get') + }) + .post((req, res) => { + res.send('post') + }) request(app) - .post('/foo') - .expect('post', done); - }); + .post('/foo') + .expect('post', done) + }) - it('should support dynamic routes', function(done){ - var app = express(); + it('should support dynamic routes', (done) => { + const app = express() app.route('/:foo') - .get(function(req, res) { - res.send(req.params.foo); - }); + .get((req, res) => { + res.send(req.params.foo) + }) request(app) - .get('/test') - .expect('test', done); - }); + .get('/test') + .expect('test', done) + }) - it('should not error on empty routes', function(done){ - var app = express(); + it('should not error on empty routes', (done) => { + const app = express() - app.route('/:foo'); + app.route('/:foo') request(app) - .get('/test') - .expect(404, done); - }); + .get('/test') + .expect(404, done) + }) - describe('promise support', function () { - it('should pass rejected promise value', function (done) { - var app = express() - var route = app.route('/foo') + describe('promise support', () => { + it('should pass rejected promise value', (done) => { + const app = express() + const route = app.route('/foo') - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all((req, res, next) => Promise.reject(new Error('boom!'))) - route.all(function helloWorld (req, res) { + route.all((req, res) => { res.send('hello, world!') }) - route.all(function handleError (err, req, res, next) { + route.all((err, req, res, next) => { res.status(500) res.send('caught: ' + err.message) }) request(app) - .get('/foo') - .expect(500, 'caught: boom!', done) + .get('/foo') + .expect(500, 'caught: boom!', done) }) - it('should pass rejected promise without value', function (done) { - var app = express() - var route = app.route('/foo') + it('should pass rejected promise without value', (done) => { + const app = express() + const route = app.route('/foo') - route.all(function createError (req, res, next) { - return Promise.reject() - }) + route.all((req, res, next) => + // eslint-disable-next-line prefer-promise-reject-errors + Promise.reject() + ) - route.all(function helloWorld (req, res) { + route.all((req, res) => { res.send('hello, world!') }) - route.all(function handleError (err, req, res, next) { + route.all((err, req, res, next) => { res.status(500) res.send('caught: ' + err.message) }) request(app) - .get('/foo') - .expect(500, 'caught: Rejected promise', done) + .get('/foo') + .expect(500, 'caught: Rejected promise', done) }) - it('should ignore resolved promise', function (done) { - var app = express() - var route = app.route('/foo') + it('should ignore resolved promise', (done) => { + const app = express() + const route = app.route('/foo') - route.all(function createError (req, res, next) { + route.all((req, res, next) => { res.send('saw GET /foo') return Promise.resolve('foo') }) - route.all(function () { + route.all(() => { done(new Error('Unexpected route invoke')) }) request(app) - .get('/foo') - .expect(200, 'saw GET /foo', done) + .get('/foo') + .expect(200, 'saw GET /foo', done) }) - describe('error handling', function () { - it('should pass rejected promise value', function (done) { - var app = express() - var route = app.route('/foo') + describe('error handling', () => { + it('should pass rejected promise value', (done) => { + const app = express() + const route = app.route('/foo') - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all((req, res, next) => Promise.reject(new Error('boom!'))) - route.all(function handleError (err, req, res, next) { - return Promise.reject(new Error('caught: ' + err.message)) - }) + route.all((err, req, res, next) => Promise.reject(new Error('caught: ' + err.message))) - route.all(function handleError (err, req, res, next) { + route.all((err, req, res, next) => { res.status(500) res.send('caught again: ' + err.message) }) request(app) - .get('/foo') - .expect(500, 'caught again: caught: boom!', done) + .get('/foo') + .expect(500, 'caught again: caught: boom!', done) }) - it('should pass rejected promise without value', function (done) { - var app = express() - var route = app.route('/foo') + it('should pass rejected promise without value', (done) => { + const app = express() + const route = app.route('/foo') - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all((req, res, next) => Promise.reject(new Error('boom!'))) - route.all(function handleError (err, req, res, next) { - return Promise.reject() - }) + route.all((err, req, res, next) => + // eslint-disable-next-line prefer-promise-reject-errors + Promise.reject() + ) - route.all(function handleError (err, req, res, next) { + route.all((err, req, res, next) => { res.status(500) res.send('caught again: ' + err.message) }) request(app) - .get('/foo') - .expect(500, 'caught again: Rejected promise', done) + .get('/foo') + .expect(500, 'caught again: Rejected promise', done) }) - it('should ignore resolved promise', function (done) { - var app = express() - var route = app.route('/foo') + it('should ignore resolved promise', (done) => { + const app = express() + const route = app.route('/foo') - route.all(function createError (req, res, next) { - return Promise.reject(new Error('boom!')) - }) + route.all((req, res, next) => Promise.reject(new Error('boom!'))) - route.all(function handleError (err, req, res, next) { + route.all((err, req, res, next) => { res.status(500) res.send('caught: ' + err.message) return Promise.resolve('foo') }) - route.all(function () { + route.all(() => { done(new Error('Unexpected route invoke')) }) request(app) - .get('/foo') - .expect(500, 'caught: boom!', done) + .get('/foo') + .expect(500, 'caught: boom!', done) }) }) }) -}); +}) diff --git a/test/app.router.js b/test/app.router.js index 6e7be684e55..d181a3219dc 100644 --- a/test/app.router.js +++ b/test/app.router.js @@ -1,80 +1,79 @@ 'use strict' -var after = require('after'); -var express = require('../') - , request = require('supertest') - , assert = require('node:assert') - , methods = require('../lib/utils').methods; +const after = require('after') +const express = require('../') +const request = require('supertest') +const assert = require('node:assert') +const { methods } = require('../lib/utils') -var shouldSkipQuery = require('./support/utils').shouldSkipQuery +const { shouldSkipQuery } = require('./support/utils') -describe('app.router', function () { - it('should restore req.params after leaving router', function (done) { - var app = express(); - var router = new express.Router(); +describe('app.router', () => { + it('should restore req.params after leaving router', (done) => { + const app = express() + const router = new express.Router() - function handler1(req, res, next) { - res.setHeader('x-user-id', String(req.params.id)); + function handler1 (req, res, next) { + res.setHeader('x-user-id', String(req.params.id)) next() } - function handler2(req, res) { - res.send(req.params.id); + function handler2 (req, res) { + res.send(req.params.id) } - router.use(function (req, res, next) { - res.setHeader('x-router', String(req.params.id)); - next(); - }); + router.use((req, res, next) => { + res.setHeader('x-router', String(req.params.id)) + next() + }) - app.get('/user/:id', handler1, router, handler2); + app.get('/user/:id', handler1, router, handler2) request(app) .get('/user/1') .expect('x-router', 'undefined') .expect('x-user-id', '1') - .expect(200, '1', done); + .expect(200, '1', done) }) - describe('methods', function () { - methods.forEach(function (method) { - if (method === 'connect') return; + describe('methods', () => { + methods.forEach((method) => { + if (method === 'connect') return it('should include ' + method.toUpperCase(), function (done) { if (method === 'query' && shouldSkipQuery(process.versions.node)) { this.skip() } - var app = express(); + const app = express() - app[method]('/foo', function (req, res) { + app[method]('/foo', (req, res) => { res.send(method) - }); + }) - request(app) - [method]('/foo') + request(app)[method]('/foo') .expect(200, done) }) - it('should reject numbers for app.' + method, function () { - var app = express(); - assert.throws(app[method].bind(app, '/', 3), /argument handler must be a function/); + it('should reject numbers for app.' + method, () => { + const app = express() + assert.throws(app[method].bind(app, '/', 3), /argument handler must be a function/) }) - }); + }) - it('should re-route when method is altered', function (done) { - var app = express(); - var cb = after(3, done); + it('should re-route when method is altered', (done) => { + const app = express() + const cb = after(3, done) - app.use(function (req, res, next) { - if (req.method !== 'POST') return next(); - req.method = 'DELETE'; - res.setHeader('X-Method-Altered', '1'); - next(); - }); + app.use((req, res, next) => { + if (req.method !== 'POST') return next() + req.method = 'DELETE' + res.setHeader('X-Method-Altered', '1') + next() + }) - app.delete('/', function (req, res) { - res.end('deleted everything'); - }); + app.delete('/', (req, res) => { + res.end('deleted everything') + }) request(app) .get('/') @@ -82,157 +81,158 @@ describe('app.router', function () { request(app) .delete('/') - .expect(200, 'deleted everything', cb); + .expect(200, 'deleted everything', cb) request(app) .post('/') .expect('X-Method-Altered', '1') - .expect(200, 'deleted everything', cb); - }); + .expect(200, 'deleted everything', cb) + }) }) - describe('decode params', function () { - it('should decode correct params', function (done) { - var app = express(); + describe('decode params', () => { + it('should decode correct params', (done) => { + const app = express() - app.get('/:name', function (req, res) { - res.send(req.params.name); - }); + app.get('/:name', (req, res) => { + res.send(req.params.name) + }) request(app) .get('/foo%2Fbar') - .expect('foo/bar', done); + .expect('foo/bar', done) }) - it('should not accept params in malformed paths', function (done) { - var app = express(); + it('should not accept params in malformed paths', (done) => { + const app = express() - app.get('/:name', function (req, res) { - res.send(req.params.name); - }); + app.get('/:name', (req, res) => { + res.send(req.params.name) + }) request(app) .get('/%foobar') - .expect(400, done); + .expect(400, done) }) - it('should not decode spaces', function (done) { - var app = express(); + it('should not decode spaces', (done) => { + const app = express() - app.get('/:name', function (req, res) { - res.send(req.params.name); - }); + app.get('/:name', (req, res) => { + res.send(req.params.name) + }) request(app) .get('/foo+bar') - .expect('foo+bar', done); + .expect('foo+bar', done) }) - it('should work with unicode', function (done) { - var app = express(); + it('should work with unicode', (done) => { + const app = express() - app.get('/:name', function (req, res) { - res.send(req.params.name); - }); + app.get('/:name', (req, res) => { + res.send(req.params.name) + }) request(app) .get('/%ce%b1') - .expect('\u03b1', done); + .expect('\u03b1', done) }) }) - it('should be .use()able', function (done) { - var app = express(); + it('should be .use()able', (done) => { + const app = express() - var calls = []; + const calls = [] - app.use(function (req, res, next) { - calls.push('before'); - next(); - }); + app.use((req, res, next) => { + calls.push('before') + next() + }) - app.get('/', function (req, res, next) { + app.get('/', (req, res, next) => { calls.push('GET /') - next(); - }); + next() + }) - app.use(function (req, res, next) { - calls.push('after'); + app.use((req, res, next) => { + calls.push('after') res.json(calls) - }); + }) request(app) .get('/') .expect(200, ['before', 'GET /', 'after'], done) }) - describe('when given a regexp', function () { - it('should match the pathname only', function (done) { - var app = express(); + describe('when given a regexp', () => { + it('should match the pathname only', (done) => { + const app = express() - app.get(/^\/user\/[0-9]+$/, function (req, res) { - res.end('user'); - }); + app.get(/^\/user\/[0-9]+$/, (req, res) => { + res.end('user') + }) request(app) .get('/user/12?foo=bar') - .expect('user', done); + .expect('user', done) }) - it('should populate req.params with the captures', function (done) { - var app = express(); + it('should populate req.params with the captures', (done) => { + const app = express() - app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, function (req, res) { - var id = req.params[0] - , op = req.params[1]; - res.end(op + 'ing user ' + id); - }); + app.get(/^\/user\/([0-9]+)\/(view|edit)?$/, (req, res) => { + const id = req.params[0] + const op = req.params[1] + res.end(op + 'ing user ' + id) + }) request(app) .get('/user/10/edit') - .expect('editing user 10', done); + .expect('editing user 10', done) }) if (supportsRegexp('(?.*)')) { - it('should populate req.params with named captures', function (done) { - var app = express(); - var re = new RegExp('^/user/(?[0-9]+)/(view|edit)?$'); - - app.get(re, function (req, res) { - var id = req.params.userId - , op = req.params[0]; - res.end(op + 'ing user ' + id); - }); + it('should populate req.params with named captures', (done) => { + const app = express() + // eslint-disable-next-line prefer-regex-literals + const re = new RegExp('^/user/(?[0-9]+)/(view|edit)?$') + + app.get(re, (req, res) => { + const id = req.params.userId + const op = req.params[0] + res.end(op + 'ing user ' + id) + }) request(app) .get('/user/10/edit') - .expect('editing user 10', done); + .expect('editing user 10', done) }) } - it('should ensure regexp matches path prefix', function (done) { - var app = express() - var p = [] + it('should ensure regexp matches path prefix', (done) => { + const app = express() + const p = [] - app.use(/\/api.*/, function (req, res, next) { + app.use(/\/api.*/, (req, res, next) => { p.push('a') next() }) - app.use(/api/, function (req, res, next) { + app.use(/api/, (req, res, next) => { p.push('b') next() }) - app.use(/\/test/, function (req, res, next) { + app.use(/\/test/, (req, res, next) => { p.push('c') next() }) - app.use(function (req, res) { + app.use((req, res) => { res.end() }) request(app) .get('/test/api/1234') - .expect(200, function (err) { + .expect(200, (err) => { if (err) return done(err) assert.deepEqual(p, ['c']) done() @@ -240,472 +240,472 @@ describe('app.router', function () { }) }) - describe('case sensitivity', function () { - it('should be disabled by default', function (done) { - var app = express(); + describe('case sensitivity', () => { + it('should be disabled by default', (done) => { + const app = express() - app.get('/user', function (req, res) { - res.end('tj'); - }); + app.get('/user', (req, res) => { + res.end('tj') + }) request(app) .get('/USER') - .expect('tj', done); + .expect('tj', done) }) - describe('when "case sensitive routing" is enabled', function () { - it('should match identical casing', function (done) { - var app = express(); + describe('when "case sensitive routing" is enabled', () => { + it('should match identical casing', (done) => { + const app = express() - app.enable('case sensitive routing'); + app.enable('case sensitive routing') - app.get('/uSer', function (req, res) { - res.end('tj'); - }); + app.get('/uSer', (req, res) => { + res.end('tj') + }) request(app) .get('/uSer') - .expect('tj', done); + .expect('tj', done) }) - it('should not match otherwise', function (done) { - var app = express(); + it('should not match otherwise', (done) => { + const app = express() - app.enable('case sensitive routing'); + app.enable('case sensitive routing') - app.get('/uSer', function (req, res) { - res.end('tj'); - }); + app.get('/uSer', (req, res) => { + res.end('tj') + }) request(app) .get('/user') - .expect(404, done); + .expect(404, done) }) }) }) - describe('params', function () { - it('should overwrite existing req.params by default', function (done) { - var app = express(); - var router = new express.Router(); + describe('params', () => { + it('should overwrite existing req.params by default', (done) => { + const app = express() + const router = new express.Router() - router.get('/:action', function (req, res) { - res.send(req.params); - }); + router.get('/:action', (req, res) => { + res.send(req.params) + }) - app.use('/user/:user', router); + app.use('/user/:user', router) request(app) .get('/user/1/get') - .expect(200, '{"action":"get"}', done); + .expect(200, '{"action":"get"}', done) }) - it('should allow merging existing req.params', function (done) { - var app = express(); - var router = new express.Router({ mergeParams: true }); + it('should allow merging existing req.params', (done) => { + const app = express() + const router = new express.Router({ mergeParams: true }) - router.get('/:action', function (req, res) { - var keys = Object.keys(req.params).sort(); - res.send(keys.map(function (k) { return [k, req.params[k]] })); - }); + router.get('/:action', (req, res) => { + const keys = Object.keys(req.params).sort() + res.send(keys.map((k) => [k, req.params[k]])) + }) - app.use('/user/:user', router); + app.use('/user/:user', router) request(app) .get('/user/tj/get') - .expect(200, '[["action","get"],["user","tj"]]', done); + .expect(200, '[["action","get"],["user","tj"]]', done) }) - it('should use params from router', function (done) { - var app = express(); - var router = new express.Router({ mergeParams: true }); + it('should use params from router', (done) => { + const app = express() + const router = new express.Router({ mergeParams: true }) - router.get('/:thing', function (req, res) { - var keys = Object.keys(req.params).sort(); - res.send(keys.map(function (k) { return [k, req.params[k]] })); - }); + router.get('/:thing', (req, res) => { + const keys = Object.keys(req.params).sort() + res.send(keys.map((k) => [k, req.params[k]])) + }) - app.use('/user/:thing', router); + app.use('/user/:thing', router) request(app) .get('/user/tj/get') - .expect(200, '[["thing","get"]]', done); + .expect(200, '[["thing","get"]]', done) }) - it('should merge numeric indices req.params', function (done) { - var app = express(); - var router = new express.Router({ mergeParams: true }); + it('should merge numeric indices req.params', (done) => { + const app = express() + const router = new express.Router({ mergeParams: true }) - router.get(/^\/(.*)\.(.*)/, function (req, res) { - var keys = Object.keys(req.params).sort(); - res.send(keys.map(function (k) { return [k, req.params[k]] })); - }); + router.get(/^\/(.*)\.(.*)/, (req, res) => { + const keys = Object.keys(req.params).sort() + res.send(keys.map((k) => [k, req.params[k]])) + }) - app.use(/^\/user\/id:(\d+)/, router); + app.use(/^\/user\/id:(\d+)/, router) request(app) .get('/user/id:10/profile.json') - .expect(200, '[["0","10"],["1","profile"],["2","json"]]', done); + .expect(200, '[["0","10"],["1","profile"],["2","json"]]', done) }) - it('should merge numeric indices req.params when more in parent', function (done) { - var app = express(); - var router = new express.Router({ mergeParams: true }); + it('should merge numeric indices req.params when more in parent', (done) => { + const app = express() + const router = new express.Router({ mergeParams: true }) - router.get(/\/(.*)/, function (req, res) { - var keys = Object.keys(req.params).sort(); - res.send(keys.map(function (k) { return [k, req.params[k]] })); - }); + router.get(/\/(.*)/, (req, res) => { + const keys = Object.keys(req.params).sort() + res.send(keys.map((k) => [k, req.params[k]])) + }) - app.use(/^\/user\/id:(\d+)\/name:(\w+)/, router); + app.use(/^\/user\/id:(\d+)\/name:(\w+)/, router) request(app) .get('/user/id:10/name:tj/profile') - .expect(200, '[["0","10"],["1","tj"],["2","profile"]]', done); + .expect(200, '[["0","10"],["1","tj"],["2","profile"]]', done) }) - it('should merge numeric indices req.params when parent has same number', function (done) { - var app = express(); - var router = new express.Router({ mergeParams: true }); + it('should merge numeric indices req.params when parent has same number', (done) => { + const app = express() + const router = new express.Router({ mergeParams: true }) - router.get(/\/name:(\w+)/, function (req, res) { - var keys = Object.keys(req.params).sort(); - res.send(keys.map(function (k) { return [k, req.params[k]] })); - }); + router.get(/\/name:(\w+)/, (req, res) => { + const keys = Object.keys(req.params).sort() + res.send(keys.map((k) => [k, req.params[k]])) + }) - app.use(/\/user\/id:(\d+)/, router); + app.use(/\/user\/id:(\d+)/, router) request(app) .get('/user/id:10/name:tj') - .expect(200, '[["0","10"],["1","tj"]]', done); + .expect(200, '[["0","10"],["1","tj"]]', done) }) - it('should ignore invalid incoming req.params', function (done) { - var app = express(); - var router = new express.Router({ mergeParams: true }); + it('should ignore invalid incoming req.params', (done) => { + const app = express() + const router = new express.Router({ mergeParams: true }) - router.get('/:name', function (req, res) { - var keys = Object.keys(req.params).sort(); - res.send(keys.map(function (k) { return [k, req.params[k]] })); - }); + router.get('/:name', (req, res) => { + const keys = Object.keys(req.params).sort() + res.send(keys.map((k) => [k, req.params[k]])) + }) - app.use('/user/', function (req, res, next) { - req.params = 3; // wat? - router(req, res, next); - }); + app.use('/user/', (req, res, next) => { + req.params = 3 // wat? + router(req, res, next) + }) request(app) .get('/user/tj') - .expect(200, '[["name","tj"]]', done); + .expect(200, '[["name","tj"]]', done) }) - it('should restore req.params', function (done) { - var app = express(); - var router = new express.Router({ mergeParams: true }); + it('should restore req.params', (done) => { + const app = express() + const router = new express.Router({ mergeParams: true }) - router.get(/\/user:(\w+)\//, function (req, res, next) { - next(); - }); + router.get(/\/user:(\w+)\//, (req, res, next) => { + next() + }) - app.use(/\/user\/id:(\d+)/, function (req, res, next) { - router(req, res, function (err) { - var keys = Object.keys(req.params).sort(); - res.send(keys.map(function (k) { return [k, req.params[k]] })); - }); - }); + app.use(/\/user\/id:(\d+)/, (req, res, next) => { + router(req, res, (err) => { + const keys = Object.keys(req.params).sort() + res.send(keys.map((k) => [k, req.params[k]])) + }) + }) request(app) .get('/user/id:42/user:tj/profile') - .expect(200, '[["0","42"]]', done); + .expect(200, '[["0","42"]]', done) }) }) - describe('trailing slashes', function () { - it('should be optional by default', function (done) { - var app = express(); + describe('trailing slashes', () => { + it('should be optional by default', (done) => { + const app = express() - app.get('/user', function (req, res) { - res.end('tj'); - }); + app.get('/user', (req, res) => { + res.end('tj') + }) request(app) .get('/user/') - .expect('tj', done); + .expect('tj', done) }) - describe('when "strict routing" is enabled', function () { - it('should match trailing slashes', function (done) { - var app = express(); + describe('when "strict routing" is enabled', () => { + it('should match trailing slashes', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.get('/user/', function (req, res) { - res.end('tj'); - }); + app.get('/user/', (req, res) => { + res.end('tj') + }) request(app) .get('/user/') - .expect('tj', done); + .expect('tj', done) }) - it('should pass-though middleware', function (done) { - var app = express(); + it('should pass-though middleware', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.use(function (req, res, next) { - res.setHeader('x-middleware', 'true'); - next(); - }); + app.use((req, res, next) => { + res.setHeader('x-middleware', 'true') + next() + }) - app.get('/user/', function (req, res) { - res.end('tj'); - }); + app.get('/user/', (req, res) => { + res.end('tj') + }) request(app) .get('/user/') .expect('x-middleware', 'true') - .expect(200, 'tj', done); + .expect(200, 'tj', done) }) - it('should pass-though mounted middleware', function (done) { - var app = express(); + it('should pass-though mounted middleware', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.use('/user/', function (req, res, next) { - res.setHeader('x-middleware', 'true'); - next(); - }); + app.use('/user/', (req, res, next) => { + res.setHeader('x-middleware', 'true') + next() + }) - app.get('/user/test/', function (req, res) { - res.end('tj'); - }); + app.get('/user/test/', (req, res) => { + res.end('tj') + }) request(app) .get('/user/test/') .expect('x-middleware', 'true') - .expect(200, 'tj', done); + .expect(200, 'tj', done) }) - it('should match no slashes', function (done) { - var app = express(); + it('should match no slashes', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.get('/user', function (req, res) { - res.end('tj'); - }); + app.get('/user', (req, res) => { + res.end('tj') + }) request(app) .get('/user') - .expect('tj', done); + .expect('tj', done) }) - it('should match middleware when omitting the trailing slash', function (done) { - var app = express(); + it('should match middleware when omitting the trailing slash', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.use('/user/', function (req, res) { - res.end('tj'); - }); + app.use('/user/', (req, res) => { + res.end('tj') + }) request(app) .get('/user') - .expect(200, 'tj', done); + .expect(200, 'tj', done) }) - it('should match middleware', function (done) { - var app = express(); + it('should match middleware', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.use('/user', function (req, res) { - res.end('tj'); - }); + app.use('/user', (req, res) => { + res.end('tj') + }) request(app) .get('/user') - .expect(200, 'tj', done); + .expect(200, 'tj', done) }) - it('should match middleware when adding the trailing slash', function (done) { - var app = express(); + it('should match middleware when adding the trailing slash', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.use('/user', function (req, res) { - res.end('tj'); - }); + app.use('/user', (req, res) => { + res.end('tj') + }) request(app) .get('/user/') - .expect(200, 'tj', done); + .expect(200, 'tj', done) }) - it('should fail when omitting the trailing slash', function (done) { - var app = express(); + it('should fail when omitting the trailing slash', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.get('/user/', function (req, res) { - res.end('tj'); - }); + app.get('/user/', (req, res) => { + res.end('tj') + }) request(app) .get('/user') - .expect(404, done); + .expect(404, done) }) - it('should fail when adding the trailing slash', function (done) { - var app = express(); + it('should fail when adding the trailing slash', (done) => { + const app = express() - app.enable('strict routing'); + app.enable('strict routing') - app.get('/user', function (req, res) { - res.end('tj'); - }); + app.get('/user', (req, res) => { + res.end('tj') + }) request(app) .get('/user/') - .expect(404, done); + .expect(404, done) }) }) }) - it('should allow literal "."', function (done) { - var app = express(); + it('should allow literal "."', (done) => { + const app = express() - app.get('/api/users/:from..:to', function (req, res) { - var from = req.params.from - , to = req.params.to; + app.get('/api/users/:from..:to', (req, res) => { + const from = req.params.from + const to = req.params.to - res.end('users from ' + from + ' to ' + to); - }); + res.end('users from ' + from + ' to ' + to) + }) request(app) .get('/api/users/1..50') - .expect('users from 1 to 50', done); + .expect('users from 1 to 50', done) }) - describe(':name', function () { - it('should denote a capture group', function (done) { - var app = express(); + describe(':name', () => { + it('should denote a capture group', (done) => { + const app = express() - app.get('/user/:user', function (req, res) { - res.end(req.params.user); - }); + app.get('/user/:user', (req, res) => { + res.end(req.params.user) + }) request(app) .get('/user/tj') - .expect('tj', done); + .expect('tj', done) }) - it('should match a single segment only', function (done) { - var app = express(); + it('should match a single segment only', (done) => { + const app = express() - app.get('/user/:user', function (req, res) { - res.end(req.params.user); - }); + app.get('/user/:user', (req, res) => { + res.end(req.params.user) + }) request(app) .get('/user/tj/edit') - .expect(404, done); + .expect(404, done) }) - it('should allow several capture groups', function (done) { - var app = express(); + it('should allow several capture groups', (done) => { + const app = express() - app.get('/user/:user/:op', function (req, res) { - res.end(req.params.op + 'ing ' + req.params.user); - }); + app.get('/user/:user/:op', (req, res) => { + res.end(req.params.op + 'ing ' + req.params.user) + }) request(app) .get('/user/tj/edit') - .expect('editing tj', done); + .expect('editing tj', done) }) - it('should work following a partial capture group', function (done) { - var app = express(); - var cb = after(2, done); + it('should work following a partial capture group', (done) => { + const app = express() + const cb = after(2, done) - app.get('/user{s}/:user/:op', function (req, res) { - res.end(req.params.op + 'ing ' + req.params.user + (req.url.startsWith('/users') ? ' (old)' : '')); - }); + app.get('/user{s}/:user/:op', (req, res) => { + res.end(req.params.op + 'ing ' + req.params.user + (req.url.startsWith('/users') ? ' (old)' : '')) + }) request(app) .get('/user/tj/edit') - .expect('editing tj', cb); + .expect('editing tj', cb) request(app) .get('/users/tj/edit') - .expect('editing tj (old)', cb); + .expect('editing tj (old)', cb) }) - it('should work inside literal parenthesis', function (done) { - var app = express(); + it('should work inside literal parenthesis', (done) => { + const app = express() - app.get('/:user\\(:op\\)', function (req, res) { - res.end(req.params.op + 'ing ' + req.params.user); - }); + app.get('/:user\\(:op\\)', (req, res) => { + res.end(req.params.op + 'ing ' + req.params.user) + }) request(app) .get('/tj(edit)') - .expect('editing tj', done); + .expect('editing tj', done) }) - it('should work in array of paths', function (done) { - var app = express(); - var cb = after(2, done); + it('should work in array of paths', (done) => { + const app = express() + const cb = after(2, done) - app.get(['/user/:user/poke', '/user/:user/pokes'], function (req, res) { - res.end('poking ' + req.params.user); - }); + app.get(['/user/:user/poke', '/user/:user/pokes'], (req, res) => { + res.end('poking ' + req.params.user) + }) request(app) .get('/user/tj/poke') - .expect('poking tj', cb); + .expect('poking tj', cb) request(app) .get('/user/tj/pokes') - .expect('poking tj', cb); + .expect('poking tj', cb) }) }) - describe(':name?', function () { - it('should denote an optional capture group', function (done) { - var app = express(); + describe(':name?', () => { + it('should denote an optional capture group', (done) => { + const app = express() - app.get('/user/:user{/:op}', function (req, res) { - var op = req.params.op || 'view'; - res.end(op + 'ing ' + req.params.user); - }); + app.get('/user/:user{/:op}', (req, res) => { + const op = req.params.op || 'view' + res.end(op + 'ing ' + req.params.user) + }) request(app) .get('/user/tj') - .expect('viewing tj', done); + .expect('viewing tj', done) }) - it('should populate the capture group', function (done) { - var app = express(); + it('should populate the capture group', (done) => { + const app = express() - app.get('/user/:user{/:op}', function (req, res) { - var op = req.params.op || 'view'; - res.end(op + 'ing ' + req.params.user); - }); + app.get('/user/:user{/:op}', (req, res) => { + const op = req.params.op || 'view' + res.end(op + 'ing ' + req.params.user) + }) request(app) .get('/user/tj/edit') - .expect('editing tj', done); + .expect('editing tj', done) }) }) - describe(':name*', function () { - it('should match one segment', function (done) { - var app = express() + describe(':name*', () => { + it('should match one segment', (done) => { + const app = express() - app.get('/user/*user', function (req, res) { + app.get('/user/*user', (req, res) => { res.end(req.params.user[0]) }) @@ -714,10 +714,10 @@ describe('app.router', function () { .expect('122', done) }) - it('should match many segments', function (done) { - var app = express() + it('should match many segments', (done) => { + const app = express() - app.get('/user/*user', function (req, res) { + app.get('/user/*user', (req, res) => { res.end(req.params.user.join('/')) }) @@ -726,10 +726,10 @@ describe('app.router', function () { .expect('1/2/3/4', done) }) - it('should match zero segments', function (done) { - var app = express() + it('should match zero segments', (done) => { + const app = express() - app.get('/user{/*user}', function (req, res) { + app.get('/user{/*user}', (req, res) => { res.end(req.params.user) }) @@ -739,11 +739,11 @@ describe('app.router', function () { }) }) - describe(':name+', function () { - it('should match one segment', function (done) { - var app = express() + describe(':name+', () => { + it('should match one segment', (done) => { + const app = express() - app.get('/user/*user', function (req, res) { + app.get('/user/*user', (req, res) => { res.end(req.params.user[0]) }) @@ -752,10 +752,10 @@ describe('app.router', function () { .expect(200, '122', done) }) - it('should match many segments', function (done) { - var app = express() + it('should match many segments', (done) => { + const app = express() - app.get('/user/*user', function (req, res) { + app.get('/user/*user', (req, res) => { res.end(req.params.user.join('/')) }) @@ -764,10 +764,10 @@ describe('app.router', function () { .expect(200, '1/2/3/4', done) }) - it('should not match zero segments', function (done) { - var app = express() + it('should not match zero segments', (done) => { + const app = express() - app.get('/user/*user', function (req, res) { + app.get('/user/*user', (req, res) => { res.end(req.params.user) }) @@ -777,14 +777,14 @@ describe('app.router', function () { }) }) - describe('.:name', function () { - it('should denote a format', function (done) { - var app = express(); - var cb = after(2, done) + describe('.:name', () => { + it('should denote a format', (done) => { + const app = express() + const cb = after(2, done) - app.get('/:name.:format', function (req, res) { - res.end(req.params.name + ' as ' + req.params.format); - }); + app.get('/:name.:format', (req, res) => { + res.end(req.params.name + ' as ' + req.params.format) + }) request(app) .get('/foo.json') @@ -796,14 +796,14 @@ describe('app.router', function () { }) }) - describe('.:name?', function () { - it('should denote an optional format', function (done) { - var app = express(); - var cb = after(2, done) + describe('.:name?', () => { + it('should denote an optional format', (done) => { + const app = express() + const cb = after(2, done) - app.get('/:name{.:format}', function (req, res) { - res.end(req.params.name + ' as ' + (req.params.format || 'html')); - }); + app.get('/:name{.:format}', (req, res) => { + res.end(req.params.name + ' as ' + (req.params.format || 'html')) + }) request(app) .get('/foo') @@ -815,29 +815,29 @@ describe('app.router', function () { }) }) - describe('when next() is called', function () { - it('should continue lookup', function (done) { - var app = express() - , calls = []; + describe('when next() is called', () => { + it('should continue lookup', (done) => { + const app = express() + const calls = [] - app.get('/foo{/:bar}', function (req, res, next) { - calls.push('/foo/:bar?'); - next(); - }); + app.get('/foo{/:bar}', (req, res, next) => { + calls.push('/foo/:bar?') + next() + }) - app.get('/bar', function () { - assert(0); - }); + app.get('/bar', () => { + assert(0) + }) - app.get('/foo', function (req, res, next) { - calls.push('/foo'); - next(); - }); + app.get('/foo', (req, res, next) => { + calls.push('/foo') + next() + }) - app.get('/foo', function (req, res) { - calls.push('/foo 2'); + app.get('/foo', (req, res) => { + calls.push('/foo 2') res.json(calls) - }); + }) request(app) .get('/foo') @@ -845,20 +845,20 @@ describe('app.router', function () { }) }) - describe('when next("route") is called', function () { - it('should jump to next route', function (done) { - var app = express() + describe('when next("route") is called', () => { + it('should jump to next route', (done) => { + const app = express() - function fn(req, res, next) { + function fn (req, res, next) { res.set('X-Hit', '1') next('route') } - app.get('/foo', fn, function (req, res) { + app.get('/foo', fn, (req, res) => { res.end('failure') - }); + }) - app.get('/foo', function (req, res) { + app.get('/foo', (req, res) => { res.end('success') }) @@ -869,27 +869,27 @@ describe('app.router', function () { }) }) - describe('when next("router") is called', function () { - it('should jump out of router', function (done) { - var app = express() - var router = express.Router() + describe('when next("router") is called', () => { + it('should jump out of router', (done) => { + const app = express() + const router = express.Router() - function fn(req, res, next) { + function fn (req, res, next) { res.set('X-Hit', '1') next('router') } - router.get('/foo', fn, function (req, res) { + router.get('/foo', fn, (req, res) => { res.end('failure') }) - router.get('/foo', function (req, res) { + router.get('/foo', (req, res) => { res.end('failure') }) app.use(router) - app.get('/foo', function (req, res) { + app.get('/foo', (req, res) => { res.end('success') }) @@ -900,32 +900,32 @@ describe('app.router', function () { }) }) - describe('when next(err) is called', function () { - it('should break out of app.router', function (done) { - var app = express() - , calls = []; + describe('when next(err) is called', () => { + it('should break out of app.router', (done) => { + const app = express() + const calls = [] - app.get('/foo{/:bar}', function (req, res, next) { - calls.push('/foo/:bar?'); - next(); - }); + app.get('/foo{/:bar}', (req, res, next) => { + calls.push('/foo/:bar?') + next() + }) - app.get('/bar', function () { - assert(0); - }); + app.get('/bar', () => { + assert(0) + }) - app.get('/foo', function (req, res, next) { - calls.push('/foo'); - next(new Error('fail')); - }); + app.get('/foo', (req, res, next) => { + calls.push('/foo') + next(new Error('fail')) + }) - app.get('/foo', function () { - assert(0); - }); + app.get('/foo', () => { + assert(0) + }) - app.use(function (err, req, res, next) { + app.use((err, req, res, next) => { res.json({ - calls: calls, + calls, error: err.message }) }) @@ -935,25 +935,25 @@ describe('app.router', function () { .expect(200, { calls: ['/foo/:bar?', '/foo'], error: 'fail' }, done) }) - it('should call handler in same route, if exists', function (done) { - var app = express(); + it('should call handler in same route, if exists', (done) => { + const app = express() - function fn1(req, res, next) { - next(new Error('boom!')); + function fn1 (req, res, next) { + next(new Error('boom!')) } - function fn2(req, res, next) { - res.send('foo here'); + function fn2 (req, res, next) { + res.send('foo here') } - function fn3(err, req, res, next) { - res.send('route go ' + err.message); + function fn3 (err, req, res, next) { + res.send('route go ' + err.message) } - app.get('/foo', fn1, fn2, fn3); + app.get('/foo', fn1, fn2, fn3) - app.use(function (err, req, res, next) { - res.end('error!'); + app.use((err, req, res, next) => { + res.end('error!') }) request(app) @@ -962,16 +962,14 @@ describe('app.router', function () { }) }) - describe('promise support', function () { - it('should pass rejected promise value', function (done) { - var app = express() - var router = new express.Router() + describe('promise support', () => { + it('should pass rejected promise value', (done) => { + const app = express() + const router = new express.Router() - router.use(function createError(req, res, next) { - return Promise.reject(new Error('boom!')) - }) + router.use((req, res, next) => Promise.reject(new Error('boom!'))) - router.use(function sawError(err, req, res, next) { + router.use((err, req, res, next) => { res.send('saw ' + err.name + ': ' + err.message) }) @@ -982,15 +980,16 @@ describe('app.router', function () { .expect(200, 'saw Error: boom!', done) }) - it('should pass rejected promise without value', function (done) { - var app = express() - var router = new express.Router() + it('should pass rejected promise without value', (done) => { + const app = express() + const router = new express.Router() - router.use(function createError(req, res, next) { - return Promise.reject() - }) + router.use((req, res, next) => + // eslint-disable-next-line prefer-promise-reject-errors + Promise.reject() + ) - router.use(function sawError(err, req, res, next) { + router.use((err, req, res, next) => { res.send('saw ' + err.name + ': ' + err.message) }) @@ -1001,16 +1000,16 @@ describe('app.router', function () { .expect(200, 'saw Error: Rejected promise', done) }) - it('should ignore resolved promise', function (done) { - var app = express() - var router = new express.Router() + it('should ignore resolved promise', (done) => { + const app = express() + const router = new express.Router() - router.use(function createError(req, res, next) { + router.use((req, res, next) => { res.send('saw GET /foo') return Promise.resolve('foo') }) - router.use(function () { + router.use(() => { done(new Error('Unexpected middleware invoke')) }) @@ -1021,20 +1020,16 @@ describe('app.router', function () { .expect(200, 'saw GET /foo', done) }) - describe('error handling', function () { - it('should pass rejected promise value', function (done) { - var app = express() - var router = new express.Router() + describe('error handling', () => { + it('should pass rejected promise value', (done) => { + const app = express() + const router = new express.Router() - router.use(function createError(req, res, next) { - return Promise.reject(new Error('boom!')) - }) + router.use((req, res, next) => Promise.reject(new Error('boom!'))) - router.use(function handleError(err, req, res, next) { - return Promise.reject(new Error('caught: ' + err.message)) - }) + router.use((err, req, res, next) => Promise.reject(new Error('caught: ' + err.message))) - router.use(function sawError(err, req, res, next) { + router.use((err, req, res, next) => { res.send('saw ' + err.name + ': ' + err.message) }) @@ -1045,19 +1040,18 @@ describe('app.router', function () { .expect(200, 'saw Error: caught: boom!', done) }) - it('should pass rejected promise without value', function (done) { - var app = express() - var router = new express.Router() + it('should pass rejected promise without value', (done) => { + const app = express() + const router = new express.Router() - router.use(function createError(req, res, next) { - return Promise.reject() - }) + router.use((req, res, next) => + // eslint-disable-next-line prefer-promise-reject-errors + Promise.reject() + ) - router.use(function handleError(err, req, res, next) { - return Promise.reject(new Error('caught: ' + err.message)) - }) + router.use((err, req, res, next) => Promise.reject(new Error('caught: ' + err.message))) - router.use(function sawError(err, req, res, next) { + router.use((err, req, res, next) => { res.send('saw ' + err.name + ': ' + err.message) }) @@ -1068,20 +1062,18 @@ describe('app.router', function () { .expect(200, 'saw Error: caught: Rejected promise', done) }) - it('should ignore resolved promise', function (done) { - var app = express() - var router = new express.Router() + it('should ignore resolved promise', (done) => { + const app = express() + const router = new express.Router() - router.use(function createError(req, res, next) { - return Promise.reject(new Error('boom!')) - }) + router.use((req, res, next) => Promise.reject(new Error('boom!'))) - router.use(function handleError(err, req, res, next) { + router.use((err, req, res, next) => { res.send('saw ' + err.name + ': ' + err.message) return Promise.resolve('foo') }) - router.use(function () { + router.use(() => { done(new Error('Unexpected middleware invoke')) }) @@ -1094,122 +1086,121 @@ describe('app.router', function () { }) }) - it('should allow rewriting of the url', function (done) { - var app = express(); + it('should allow rewriting of the url', (done) => { + const app = express() - app.get('/account/edit', function (req, res, next) { - req.user = { id: 12 }; // faux authenticated user - req.url = '/user/' + req.user.id + '/edit'; - next(); - }); + app.get('/account/edit', (req, res, next) => { + req.user = { id: 12 } // faux authenticated user + req.url = '/user/' + req.user.id + '/edit' + next() + }) - app.get('/user/:id/edit', function (req, res) { - res.send('editing user ' + req.params.id); - }); + app.get('/user/:id/edit', (req, res) => { + res.send('editing user ' + req.params.id) + }) request(app) .get('/account/edit') - .expect('editing user 12', done); + .expect('editing user 12', done) }) - it('should run in order added', function (done) { - var app = express(); - var path = []; - - app.get('/*path', function (req, res, next) { - path.push(0); - next(); - }); - - app.get('/user/:id', function (req, res, next) { - path.push(1); - next(); - }); - - app.use(function (req, res, next) { - path.push(2); - next(); - }); - - app.all('/user/:id', function (req, res, next) { - path.push(3); - next(); - }); - - app.get('/*splat', function (req, res, next) { - path.push(4); - next(); - }); - - app.use(function (req, res, next) { - path.push(5); + it('should run in order added', (done) => { + const app = express() + const path = [] + + app.get('/*path', (req, res, next) => { + path.push(0) + next() + }) + + app.get('/user/:id', (req, res, next) => { + path.push(1) + next() + }) + + app.use((req, res, next) => { + path.push(2) + next() + }) + + app.all('/user/:id', (req, res, next) => { + path.push(3) + next() + }) + + app.get('/*splat', (req, res, next) => { + path.push(4) + next() + }) + + app.use((req, res, next) => { + path.push(5) res.end(path.join(',')) - }); + }) request(app) .get('/user/1') - .expect(200, '0,1,2,3,4,5', done); + .expect(200, '0,1,2,3,4,5', done) }) - it('should be chainable', function () { - var app = express(); - assert.strictEqual(app.get('/', function () { }), app) + it('should be chainable', () => { + const app = express() + assert.strictEqual(app.get('/', () => { }), app) }) - it('should not use disposed router/middleware', function (done) { + it('should not use disposed router/middleware', (done) => { // more context: https://github.com/expressjs/express/issues/5743#issuecomment-2277148412 - var app = express(); - var router = new express.Router(); + const app = express() + let router = new express.Router() - router.use(function (req, res, next) { - res.setHeader('old', 'foo'); - next(); - }); + router.use((req, res, next) => { + res.setHeader('old', 'foo') + next() + }) - app.use(function (req, res, next) { - return router.handle(req, res, next); - }); + app.use((req, res, next) => router.handle(req, res, next)) - app.get('/', function (req, res, next) { - res.send('yee'); - next(); - }); + app.get('/', (req, res, next) => { + res.send('yee') + next() + }) request(app) .get('/') .expect('old', 'foo') - .expect(function (res) { + .expect((res) => { if (typeof res.headers['new'] !== 'undefined') { - throw new Error('`new` header should not be present'); + throw new Error('`new` header should not be present') } }) - .expect(200, 'yee', function (err, res) { - if (err) return done(err); + .expect(200, 'yee', (err, res) => { + if (err) return done(err) - router = new express.Router(); + router = new express.Router() - router.use(function (req, res, next) { - res.setHeader('new', 'bar'); - next(); - }); + router.use((req, res, next) => { + res.setHeader('new', 'bar') + next() + }) request(app) .get('/') .expect('new', 'bar') - .expect(function (res) { + .expect((res) => { if (typeof res.headers['old'] !== 'undefined') { - throw new Error('`old` header should not be present'); + throw new Error('`old` header should not be present') } }) - .expect(200, 'yee', done); - }); + .expect(200, 'yee', done) + }) }) }) -function supportsRegexp(source) { +function supportsRegexp (source) { try { - new RegExp(source) + // eslint-disable-next-line no-unused-vars + const _ = new RegExp(source) return true } catch (e) { return false diff --git a/test/app.routes.error.js b/test/app.routes.error.js index ed53c7857ba..3b90cea2bf5 100644 --- a/test/app.routes.error.js +++ b/test/app.routes.error.js @@ -1,62 +1,62 @@ 'use strict' -var assert = require('node:assert') -var express = require('../') - , request = require('supertest'); +const assert = require('node:assert') +const express = require('../') +const request = require('supertest') -describe('app', function(){ - describe('.VERB()', function(){ - it('should not get invoked without error handler on error', function(done) { - var app = express(); +describe('app', () => { + describe('.VERB()', () => { + it('should not get invoked without error handler on error', (done) => { + const app = express() - app.use(function(req, res, next){ + app.use((req, res, next) => { next(new Error('boom!')) - }); + }) - app.get('/bar', function(req, res){ - res.send('hello, world!'); - }); + app.get('/bar', (req, res) => { + res.send('hello, world!') + }) request(app) - .post('/bar') - .expect(500, /Error: boom!/, done); - }); - - it('should only call an error handling routing callback when an error is propagated', function(done){ - var app = express(); - - var a = false; - var b = false; - var c = false; - var d = false; - - app.get('/', function(req, res, next){ - next(new Error('fabricated error')); - }, function(req, res, next) { - a = true; - next(); - }, function(err, req, res, next){ - b = true; + .post('/bar') + .expect(500, /Error: boom!/, done) + }) + + it('should only call an error handling routing callback when an error is propagated', (done) => { + const app = express() + + let a = false + let b = false + let c = false + let d = false + + app.get('/', (req, res, next) => { + next(new Error('fabricated error')) + }, (req, res, next) => { + a = true + next() + }, (err, req, res, next) => { + b = true assert.strictEqual(err.message, 'fabricated error') - next(err); - }, function(err, req, res, next){ - c = true; + next(err) + }, (err, req, res, next) => { + c = true assert.strictEqual(err.message, 'fabricated error') - next(); - }, function(err, req, res, next){ - d = true; - next(); - }, function(req, res){ + next() + }, (err, req, res, next) => { + d = true + next() + }, (req, res) => { assert.ok(!a) assert.ok(b) assert.ok(c) assert.ok(!d) - res.sendStatus(204); - }); + res.sendStatus(204) + }) request(app) - .get('/') - .expect(204, done); + .get('/') + .expect(204, done) }) }) }) diff --git a/test/app.use.js b/test/app.use.js index 1d56aa3b029..8af7052ae5a 100644 --- a/test/app.use.js +++ b/test/app.use.js @@ -1,55 +1,55 @@ 'use strict' -var after = require('after'); -var assert = require('node:assert') -var express = require('..'); -var request = require('supertest'); +const after = require('after') +const assert = require('node:assert') +const express = require('../') +const request = require('supertest') -describe('app', function(){ - it('should emit "mount" when mounted', function(done){ - var blog = express() - , app = express(); +describe('app', () => { + it('should emit "mount" when mounted', (done) => { + const blog = express() + const app = express() - blog.on('mount', function(arg){ + blog.on('mount', (arg) => { assert.strictEqual(arg, app) - done(); - }); + done() + }) - app.use(blog); + app.use(blog) }) - describe('.use(app)', function(){ - it('should mount the app', function(done){ - var blog = express() - , app = express(); + describe('.use(app)', () => { + it('should mount the app', (done) => { + const blog = express() + const app = express() - blog.get('/blog', function(req, res){ - res.end('blog'); - }); + blog.get('/blog', (req, res) => { + res.end('blog') + }) - app.use(blog); + app.use(blog) request(app) - .get('/blog') - .expect('blog', done); + .get('/blog') + .expect('blog', done) }) - it('should support mount-points', function(done){ - var blog = express() - , forum = express() - , app = express(); - var cb = after(2, done) + it('should support mount-points', (done) => { + const blog = express() + const forum = express() + const app = express() + const cb = after(2, done) - blog.get('/', function(req, res){ - res.end('blog'); - }); + blog.get('/', (req, res) => { + res.end('blog') + }) - forum.get('/', function(req, res){ - res.end('forum'); - }); + forum.get('/', (req, res) => { + res.end('forum') + }) - app.use('/blog', blog); - app.use('/forum', forum); + app.use('/blog', blog) + app.use('/forum', forum) request(app) .get('/blog') @@ -60,483 +60,483 @@ describe('app', function(){ .expect(200, 'forum', cb) }) - it('should set the child\'s .parent', function(){ - var blog = express() - , app = express(); + it('should set the child\'s .parent', () => { + const blog = express() + const app = express() - app.use('/blog', blog); + app.use('/blog', blog) assert.strictEqual(blog.parent, app) }) - it('should support dynamic routes', function(done){ - var blog = express() - , app = express(); + it('should support dynamic routes', (done) => { + const blog = express() + const app = express() - blog.get('/', function(req, res){ - res.end('success'); - }); + blog.get('/', (req, res) => { + res.end('success') + }) - app.use('/post/:article', blog); + app.use('/post/:article', blog) request(app) - .get('/post/once-upon-a-time') - .expect('success', done); + .get('/post/once-upon-a-time') + .expect('success', done) }) - it('should support mounted app anywhere', function(done){ - var cb = after(3, done); - var blog = express() - , other = express() - , app = express(); + it('should support mounted app anywhere', (done) => { + const cb = after(3, done) + const blog = express() + const other = express() + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - blog.get('/', function(req, res){ - res.end('success'); - }); + blog.get('/', (req, res) => { + res.end('success') + }) - blog.once('mount', function (parent) { + blog.once('mount', (parent) => { assert.strictEqual(parent, app) - cb(); - }); - other.once('mount', function (parent) { + cb() + }) + other.once('mount', (parent) => { assert.strictEqual(parent, app) - cb(); - }); + cb() + }) - app.use('/post/:article', fn1, other, fn2, blog); + app.use('/post/:article', fn1, other, fn2, blog) request(app) - .get('/post/once-upon-a-time') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('success', cb); + .get('/post/once-upon-a-time') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('success', cb) }) }) - describe('.use(middleware)', function(){ - it('should accept multiple arguments', function (done) { - var app = express(); + describe('.use(middleware)', () => { + it('should accept multiple arguments', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - app.use(fn1, fn2, function fn3(req, res) { - res.setHeader('x-fn-3', 'hit'); - res.end(); - }); + app.use(fn1, fn2, (req, res) => { + res.setHeader('x-fn-3', 'hit') + res.end() + }) request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) - it('should invoke middleware for all requests', function (done) { - var app = express(); - var cb = after(3, done); + it('should invoke middleware for all requests', (done) => { + const app = express() + const cb = after(3, done) - app.use(function (req, res) { - res.send('saw ' + req.method + ' ' + req.url); - }); + app.use((req, res) => { + res.send('saw ' + req.method + ' ' + req.url) + }) request(app) - .get('/') - .expect(200, 'saw GET /', cb); + .get('/') + .expect(200, 'saw GET /', cb) request(app) - .options('/') - .expect(200, 'saw OPTIONS /', cb); + .options('/') + .expect(200, 'saw OPTIONS /', cb) request(app) - .post('/foo') - .expect(200, 'saw POST /foo', cb); + .post('/foo') + .expect(200, 'saw POST /foo', cb) }) - it('should accept array of middleware', function (done) { - var app = express(); + it('should accept array of middleware', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - function fn3(req, res, next) { - res.setHeader('x-fn-3', 'hit'); - res.end(); + function fn3 (req, res, next) { + res.setHeader('x-fn-3', 'hit') + res.end() } - app.use([fn1, fn2, fn3]); + app.use([fn1, fn2, fn3]) request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) - it('should accept multiple arrays of middleware', function (done) { - var app = express(); + it('should accept multiple arrays of middleware', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - function fn3(req, res, next) { - res.setHeader('x-fn-3', 'hit'); - res.end(); + function fn3 (req, res, next) { + res.setHeader('x-fn-3', 'hit') + res.end() } - app.use([fn1, fn2], [fn3]); + app.use([fn1, fn2], [fn3]) request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) - it('should accept nested arrays of middleware', function (done) { - var app = express(); + it('should accept nested arrays of middleware', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - function fn3(req, res, next) { - res.setHeader('x-fn-3', 'hit'); - res.end(); + function fn3 (req, res, next) { + res.setHeader('x-fn-3', 'hit') + res.end() } - app.use([[fn1], fn2], [fn3]); + app.use([[fn1], fn2], [fn3]) request(app) - .get('/') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) }) - describe('.use(path, middleware)', function(){ - it('should require middleware', function () { - var app = express() - assert.throws(function () { app.use('/') }, 'TypeError: app.use() requires a middleware function') + describe('.use(path, middleware)', () => { + it('should require middleware', () => { + const app = express() + assert.throws(() => { app.use('/') }, 'TypeError: app.use() requires a middleware function') }) - it('should reject string as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', 'foo') }, /argument handler must be a function/) + it('should reject string as middleware', () => { + const app = express() + assert.throws(() => { app.use('/', 'foo') }, /argument handler must be a function/) }) - it('should reject number as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', 42) }, /argument handler must be a function/) + it('should reject number as middleware', () => { + const app = express() + assert.throws(() => { app.use('/', 42) }, /argument handler must be a function/) }) - it('should reject null as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', null) }, /argument handler must be a function/) + it('should reject null as middleware', () => { + const app = express() + assert.throws(() => { app.use('/', null) }, /argument handler must be a function/) }) - it('should reject Date as middleware', function () { - var app = express() - assert.throws(function () { app.use('/', new Date()) }, /argument handler must be a function/) + it('should reject Date as middleware', () => { + const app = express() + assert.throws(() => { app.use('/', new Date()) }, /argument handler must be a function/) }) - it('should strip path from req.url', function (done) { - var app = express(); + it('should strip path from req.url', (done) => { + const app = express() - app.use('/foo', function (req, res) { - res.send('saw ' + req.method + ' ' + req.url); - }); + app.use('/foo', (req, res) => { + res.send('saw ' + req.method + ' ' + req.url) + }) request(app) - .get('/foo/bar') - .expect(200, 'saw GET /bar', done); + .get('/foo/bar') + .expect(200, 'saw GET /bar', done) }) - it('should accept multiple arguments', function (done) { - var app = express(); + it('should accept multiple arguments', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - app.use('/foo', fn1, fn2, function fn3(req, res) { - res.setHeader('x-fn-3', 'hit'); - res.end(); - }); + app.use('/foo', fn1, fn2, (req, res) => { + res.setHeader('x-fn-3', 'hit') + res.end() + }) request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) - it('should invoke middleware for all requests starting with path', function (done) { - var app = express(); - var cb = after(3, done); + it('should invoke middleware for all requests starting with path', (done) => { + const app = express() + const cb = after(3, done) - app.use('/foo', function (req, res) { - res.send('saw ' + req.method + ' ' + req.url); - }); + app.use('/foo', (req, res) => { + res.send('saw ' + req.method + ' ' + req.url) + }) request(app) - .get('/') - .expect(404, cb); + .get('/') + .expect(404, cb) request(app) - .post('/foo') - .expect(200, 'saw POST /', cb); + .post('/foo') + .expect(200, 'saw POST /', cb) request(app) - .post('/foo/bar') - .expect(200, 'saw POST /bar', cb); + .post('/foo/bar') + .expect(200, 'saw POST /bar', cb) }) - it('should work if path has trailing slash', function (done) { - var app = express(); - var cb = after(3, done); + it('should work if path has trailing slash', (done) => { + const app = express() + const cb = after(3, done) - app.use('/foo/', function (req, res) { - res.send('saw ' + req.method + ' ' + req.url); - }); + app.use('/foo/', (req, res) => { + res.send('saw ' + req.method + ' ' + req.url) + }) request(app) - .get('/') - .expect(404, cb); + .get('/') + .expect(404, cb) request(app) - .post('/foo') - .expect(200, 'saw POST /', cb); + .post('/foo') + .expect(200, 'saw POST /', cb) request(app) - .post('/foo/bar') - .expect(200, 'saw POST /bar', cb); + .post('/foo/bar') + .expect(200, 'saw POST /bar', cb) }) - it('should accept array of middleware', function (done) { - var app = express(); + it('should accept array of middleware', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - function fn3(req, res, next) { - res.setHeader('x-fn-3', 'hit'); - res.end(); + function fn3 (req, res, next) { + res.setHeader('x-fn-3', 'hit') + res.end() } - app.use('/foo', [fn1, fn2, fn3]); + app.use('/foo', [fn1, fn2, fn3]) request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) - it('should accept multiple arrays of middleware', function (done) { - var app = express(); + it('should accept multiple arrays of middleware', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - function fn3(req, res, next) { - res.setHeader('x-fn-3', 'hit'); - res.end(); + function fn3 (req, res, next) { + res.setHeader('x-fn-3', 'hit') + res.end() } - app.use('/foo', [fn1, fn2], [fn3]); + app.use('/foo', [fn1, fn2], [fn3]) request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) - it('should accept nested arrays of middleware', function (done) { - var app = express(); + it('should accept nested arrays of middleware', (done) => { + const app = express() - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - function fn3(req, res, next) { - res.setHeader('x-fn-3', 'hit'); - res.end(); + function fn3 (req, res, next) { + res.setHeader('x-fn-3', 'hit') + res.end() } - app.use('/foo', [fn1, [fn2]], [fn3]); + app.use('/foo', [fn1, [fn2]], [fn3]) request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, done); + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, done) }) - it('should support array of paths', function (done) { - var app = express(); - var cb = after(3, done); + it('should support array of paths', (done) => { + const app = express() + const cb = after(3, done) - app.use(['/foo/', '/bar'], function (req, res) { - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); - }); + app.use(['/foo/', '/bar'], (req, res) => { + res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl) + }) request(app) - .get('/') - .expect(404, cb); + .get('/') + .expect(404, cb) request(app) - .get('/foo') - .expect(200, 'saw GET / through /foo', cb); + .get('/foo') + .expect(200, 'saw GET / through /foo', cb) request(app) - .get('/bar') - .expect(200, 'saw GET / through /bar', cb); + .get('/bar') + .expect(200, 'saw GET / through /bar', cb) }) - it('should support array of paths with middleware array', function (done) { - var app = express(); - var cb = after(2, done); + it('should support array of paths with middleware array', (done) => { + const app = express() + const cb = after(2, done) - function fn1(req, res, next) { - res.setHeader('x-fn-1', 'hit'); - next(); + function fn1 (req, res, next) { + res.setHeader('x-fn-1', 'hit') + next() } - function fn2(req, res, next) { - res.setHeader('x-fn-2', 'hit'); - next(); + function fn2 (req, res, next) { + res.setHeader('x-fn-2', 'hit') + next() } - function fn3(req, res, next) { - res.setHeader('x-fn-3', 'hit'); - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); + function fn3 (req, res, next) { + res.setHeader('x-fn-3', 'hit') + res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl) } - app.use(['/foo/', '/bar'], [[fn1], fn2], [fn3]); + app.use(['/foo/', '/bar'], [[fn1], fn2], [fn3]) request(app) - .get('/foo') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, 'saw GET / through /foo', cb); + .get('/foo') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, 'saw GET / through /foo', cb) request(app) - .get('/bar') - .expect('x-fn-1', 'hit') - .expect('x-fn-2', 'hit') - .expect('x-fn-3', 'hit') - .expect(200, 'saw GET / through /bar', cb); + .get('/bar') + .expect('x-fn-1', 'hit') + .expect('x-fn-2', 'hit') + .expect('x-fn-3', 'hit') + .expect(200, 'saw GET / through /bar', cb) }) - it('should support regexp path', function (done) { - var app = express(); - var cb = after(4, done); + it('should support regexp path', (done) => { + const app = express() + const cb = after(4, done) - app.use(/^\/[a-z]oo/, function (req, res) { - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); - }); + app.use(/^\/[a-z]oo/, (req, res) => { + res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl) + }) request(app) - .get('/') - .expect(404, cb); + .get('/') + .expect(404, cb) request(app) - .get('/foo') - .expect(200, 'saw GET / through /foo', cb); + .get('/foo') + .expect(200, 'saw GET / through /foo', cb) request(app) - .get('/zoo/bear') - .expect(200, 'saw GET /bear through /zoo/bear', cb); + .get('/zoo/bear') + .expect(200, 'saw GET /bear through /zoo/bear', cb) request(app) - .get('/get/zoo') - .expect(404, cb); + .get('/get/zoo') + .expect(404, cb) }) - it('should support empty string path', function (done) { - var app = express(); + it('should support empty string path', (done) => { + const app = express() - app.use('', function (req, res) { - res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl); - }); + app.use('', (req, res) => { + res.send('saw ' + req.method + ' ' + req.url + ' through ' + req.originalUrl) + }) request(app) - .get('/') - .expect(200, 'saw GET / through /', done); + .get('/') + .expect(200, 'saw GET / through /', done) }) }) }) diff --git a/test/config.js b/test/config.js index d004de03eaa..d65cc699d00 100644 --- a/test/config.js +++ b/test/config.js @@ -1,206 +1,206 @@ 'use strict' -var assert = require('node:assert'); -var express = require('..'); +const assert = require('node:assert') +const express = require('../') -describe('config', function () { - describe('.set()', function () { - it('should set a value', function () { - var app = express(); - app.set('foo', 'bar'); - assert.equal(app.get('foo'), 'bar'); +describe('config', () => { + describe('.set()', () => { + it('should set a value', () => { + const app = express() + app.set('foo', 'bar') + assert.equal(app.get('foo'), 'bar') }) - it('should set prototype values', function () { - var app = express() + it('should set prototype values', () => { + const app = express() app.set('hasOwnProperty', 42) assert.strictEqual(app.get('hasOwnProperty'), 42) }) - it('should return the app', function () { - var app = express(); - assert.equal(app.set('foo', 'bar'), app); + it('should return the app', () => { + const app = express() + assert.equal(app.set('foo', 'bar'), app) }) - it('should return the app when undefined', function () { - var app = express(); - assert.equal(app.set('foo', undefined), app); + it('should return the app when undefined', () => { + const app = express() + assert.equal(app.set('foo', undefined), app) }) - it('should return set value', function () { - var app = express() + it('should return set value', () => { + const app = express() app.set('foo', 'bar') assert.strictEqual(app.set('foo'), 'bar') }) - it('should return undefined for prototype values', function () { - var app = express() + it('should return undefined for prototype values', () => { + const app = express() assert.strictEqual(app.set('hasOwnProperty'), undefined) }) - describe('"etag"', function(){ - it('should throw on bad value', function(){ - var app = express(); - assert.throws(app.set.bind(app, 'etag', 42), /unknown value/); + describe('"etag"', () => { + it('should throw on bad value', () => { + const app = express() + assert.throws(app.set.bind(app, 'etag', 42), /unknown value/) }) - it('should set "etag fn"', function(){ - var app = express() - var fn = function(){} + it('should set "etag fn"', () => { + const app = express() + const fn = function () {} app.set('etag', fn) assert.equal(app.get('etag fn'), fn) }) }) - describe('"trust proxy"', function(){ - it('should set "trust proxy fn"', function(){ - var app = express() - var fn = function(){} + describe('"trust proxy"', () => { + it('should set "trust proxy fn"', () => { + const app = express() + const fn = function () {} app.set('trust proxy', fn) assert.equal(app.get('trust proxy fn'), fn) }) }) }) - describe('.get()', function(){ - it('should return undefined when unset', function(){ - var app = express(); - assert.strictEqual(app.get('foo'), undefined); + describe('.get()', () => { + it('should return undefined when unset', () => { + const app = express() + assert.strictEqual(app.get('foo'), undefined) }) - it('should return undefined for prototype values', function () { - var app = express() + it('should return undefined for prototype values', () => { + const app = express() assert.strictEqual(app.get('hasOwnProperty'), undefined) }) - it('should otherwise return the value', function(){ - var app = express(); - app.set('foo', 'bar'); - assert.equal(app.get('foo'), 'bar'); + it('should otherwise return the value', () => { + const app = express() + app.set('foo', 'bar') + assert.equal(app.get('foo'), 'bar') }) - describe('when mounted', function(){ - it('should default to the parent app', function(){ - var app = express(); - var blog = express(); + describe('when mounted', () => { + it('should default to the parent app', () => { + const app = express() + const blog = express() - app.set('title', 'Express'); - app.use(blog); - assert.equal(blog.get('title'), 'Express'); + app.set('title', 'Express') + app.use(blog) + assert.equal(blog.get('title'), 'Express') }) - it('should given precedence to the child', function(){ - var app = express(); - var blog = express(); + it('should given precedence to the child', () => { + const app = express() + const blog = express() - app.use(blog); - app.set('title', 'Express'); - blog.set('title', 'Some Blog'); + app.use(blog) + app.set('title', 'Express') + blog.set('title', 'Some Blog') - assert.equal(blog.get('title'), 'Some Blog'); + assert.equal(blog.get('title'), 'Some Blog') }) - it('should inherit "trust proxy" setting', function () { - var app = express(); - var blog = express(); + it('should inherit "trust proxy" setting', () => { + const app = express() + const blog = express() - function fn() { return false } + function fn () { return false } - app.set('trust proxy', fn); - assert.equal(app.get('trust proxy'), fn); - assert.equal(app.get('trust proxy fn'), fn); + app.set('trust proxy', fn) + assert.equal(app.get('trust proxy'), fn) + assert.equal(app.get('trust proxy fn'), fn) - app.use(blog); + app.use(blog) - assert.equal(blog.get('trust proxy'), fn); - assert.equal(blog.get('trust proxy fn'), fn); + assert.equal(blog.get('trust proxy'), fn) + assert.equal(blog.get('trust proxy fn'), fn) }) - it('should prefer child "trust proxy" setting', function () { - var app = express(); - var blog = express(); + it('should prefer child "trust proxy" setting', () => { + const app = express() + const blog = express() - function fn1() { return false } - function fn2() { return true } + function fn1 () { return false } + function fn2 () { return true } - app.set('trust proxy', fn1); - assert.equal(app.get('trust proxy'), fn1); - assert.equal(app.get('trust proxy fn'), fn1); + app.set('trust proxy', fn1) + assert.equal(app.get('trust proxy'), fn1) + assert.equal(app.get('trust proxy fn'), fn1) - blog.set('trust proxy', fn2); - assert.equal(blog.get('trust proxy'), fn2); - assert.equal(blog.get('trust proxy fn'), fn2); + blog.set('trust proxy', fn2) + assert.equal(blog.get('trust proxy'), fn2) + assert.equal(blog.get('trust proxy fn'), fn2) - app.use(blog); + app.use(blog) - assert.equal(app.get('trust proxy'), fn1); - assert.equal(app.get('trust proxy fn'), fn1); - assert.equal(blog.get('trust proxy'), fn2); - assert.equal(blog.get('trust proxy fn'), fn2); + assert.equal(app.get('trust proxy'), fn1) + assert.equal(app.get('trust proxy fn'), fn1) + assert.equal(blog.get('trust proxy'), fn2) + assert.equal(blog.get('trust proxy fn'), fn2) }) }) }) - describe('.enable()', function(){ - it('should set the value to true', function(){ - var app = express(); - assert.equal(app.enable('tobi'), app); - assert.strictEqual(app.get('tobi'), true); + describe('.enable()', () => { + it('should set the value to true', () => { + const app = express() + assert.equal(app.enable('tobi'), app) + assert.strictEqual(app.get('tobi'), true) }) - it('should set prototype values', function () { - var app = express() + it('should set prototype values', () => { + const app = express() app.enable('hasOwnProperty') assert.strictEqual(app.get('hasOwnProperty'), true) }) }) - describe('.disable()', function(){ - it('should set the value to false', function(){ - var app = express(); - assert.equal(app.disable('tobi'), app); - assert.strictEqual(app.get('tobi'), false); + describe('.disable()', () => { + it('should set the value to false', () => { + const app = express() + assert.equal(app.disable('tobi'), app) + assert.strictEqual(app.get('tobi'), false) }) - it('should set prototype values', function () { - var app = express() + it('should set prototype values', () => { + const app = express() app.disable('hasOwnProperty') assert.strictEqual(app.get('hasOwnProperty'), false) }) }) - describe('.enabled()', function(){ - it('should default to false', function(){ - var app = express(); - assert.strictEqual(app.enabled('foo'), false); + describe('.enabled()', () => { + it('should default to false', () => { + const app = express() + assert.strictEqual(app.enabled('foo'), false) }) - it('should return true when set', function(){ - var app = express(); - app.set('foo', 'bar'); - assert.strictEqual(app.enabled('foo'), true); + it('should return true when set', () => { + const app = express() + app.set('foo', 'bar') + assert.strictEqual(app.enabled('foo'), true) }) - it('should default to false for prototype values', function () { - var app = express() + it('should default to false for prototype values', () => { + const app = express() assert.strictEqual(app.enabled('hasOwnProperty'), false) }) }) - describe('.disabled()', function(){ - it('should default to true', function(){ - var app = express(); - assert.strictEqual(app.disabled('foo'), true); + describe('.disabled()', () => { + it('should default to true', () => { + const app = express() + assert.strictEqual(app.disabled('foo'), true) }) - it('should return false when set', function(){ - var app = express(); - app.set('foo', 'bar'); - assert.strictEqual(app.disabled('foo'), false); + it('should return false when set', () => { + const app = express() + app.set('foo', 'bar') + assert.strictEqual(app.disabled('foo'), false) }) - it('should default to true for prototype values', function () { - var app = express() + it('should default to true for prototype values', () => { + const app = express() assert.strictEqual(app.disabled('hasOwnProperty'), true) }) }) diff --git a/test/exports.js b/test/exports.js index fc7836c1594..8c61564a924 100644 --- a/test/exports.js +++ b/test/exports.js @@ -1,82 +1,82 @@ 'use strict' -var assert = require('node:assert') -var express = require('../'); -var request = require('supertest'); +const assert = require('node:assert') +const express = require('../') +const request = require('supertest') -describe('exports', function(){ - it('should expose Router', function(){ +describe('exports', () => { + it('should expose Router', () => { assert.strictEqual(typeof express.Router, 'function') }) - it('should expose json middleware', function () { + it('should expose json middleware', () => { assert.equal(typeof express.json, 'function') assert.equal(express.json.length, 1) }) - it('should expose raw middleware', function () { + it('should expose raw middleware', () => { assert.equal(typeof express.raw, 'function') assert.equal(express.raw.length, 1) }) - it('should expose static middleware', function () { + it('should expose static middleware', () => { assert.equal(typeof express.static, 'function') assert.equal(express.static.length, 2) }) - it('should expose text middleware', function () { + it('should expose text middleware', () => { assert.equal(typeof express.text, 'function') assert.equal(express.text.length, 1) }) - it('should expose urlencoded middleware', function () { + it('should expose urlencoded middleware', () => { assert.equal(typeof express.urlencoded, 'function') assert.equal(express.urlencoded.length, 1) }) - it('should expose the application prototype', function(){ + it('should expose the application prototype', () => { assert.strictEqual(typeof express.application, 'object') assert.strictEqual(typeof express.application.set, 'function') }) - it('should expose the request prototype', function(){ + it('should expose the request prototype', () => { assert.strictEqual(typeof express.request, 'object') assert.strictEqual(typeof express.request.accepts, 'function') }) - it('should expose the response prototype', function(){ + it('should expose the response prototype', () => { assert.strictEqual(typeof express.response, 'object') assert.strictEqual(typeof express.response.send, 'function') }) - it('should permit modifying the .application prototype', function(){ - express.application.foo = function(){ return 'bar'; }; + it('should permit modifying the .application prototype', () => { + express.application.foo = function () { return 'bar' } assert.strictEqual(express().foo(), 'bar') }) - it('should permit modifying the .request prototype', function(done){ - express.request.foo = function(){ return 'bar'; }; - var app = express(); + it('should permit modifying the .request prototype', (done) => { + express.request.foo = function () { return 'bar' } + const app = express() - app.use(function(req, res, next){ - res.end(req.foo()); - }); + app.use((req, res, next) => { + res.end(req.foo()) + }) request(app) - .get('/') - .expect('bar', done); + .get('/') + .expect('bar', done) }) - it('should permit modifying the .response prototype', function(done){ - express.response.foo = function(){ this.send('bar'); }; - var app = express(); + it('should permit modifying the .response prototype', (done) => { + express.response.foo = function () { this.send('bar') } + const app = express() - app.use(function(req, res, next){ - res.foo(); - }); + app.use((req, res, next) => { + res.foo() + }) request(app) - .get('/') - .expect('bar', done); + .get('/') + .expect('bar', done) }) }) diff --git a/test/express.json.js b/test/express.json.js index 28746bfebda..80ec62e43ae 100644 --- a/test/express.json.js +++ b/test/express.json.js @@ -1,14 +1,14 @@ 'use strict' -var assert = require('node:assert') -var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage -const { Buffer } = require('node:buffer'); +const assert = require('node:assert') +const { AsyncLocalStorage } = require('node:async_hooks') +const { Buffer } = require('node:buffer') -var express = require('..') -var request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('express.json()', function () { - it('should parse JSON', function (done) { +describe('express.json()', () => { + it('should parse JSON', (done) => { request(createApp()) .post('/') .set('Content-Type', 'application/json') @@ -16,7 +16,7 @@ describe('express.json()', function () { .expect(200, '{"user":"tobi"}', done) }) - it('should handle Content-Length: 0', function (done) { + it('should handle Content-Length: 0', (done) => { request(createApp()) .post('/') .set('Content-Type', 'application/json') @@ -24,7 +24,7 @@ describe('express.json()', function () { .expect(200, '{}', done) }) - it('should handle empty message-body', function (done) { + it('should handle empty message-body', (done) => { request(createApp()) .post('/') .set('Content-Type', 'application/json') @@ -32,7 +32,7 @@ describe('express.json()', function () { .expect(200, '{}', done) }) - it('should handle no message-body', function (done) { + it('should handle no message-body', (done) => { request(createApp()) .post('/') .set('Content-Type', 'application/json') @@ -41,7 +41,7 @@ describe('express.json()', function () { }) // The old node error message modification in body parser is catching this - it('should 400 when only whitespace', function (done) { + it('should 400 when only whitespace', (done) => { request(createApp()) .post('/') .set('Content-Type', 'application/json') @@ -49,17 +49,17 @@ describe('express.json()', function () { .expect(400, '[entity.parse.failed] ' + parseError(' \n'), done) }) - it('should 400 when invalid content-length', function (done) { - var app = express() + it('should 400 when invalid content-length', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { req.headers['content-length'] = '20' // bad length next() }) app.use(express.json()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -70,13 +70,13 @@ describe('express.json()', function () { .expect(400, /content length/, done) }) - it('should handle duplicated middleware', function (done) { - var app = express() + it('should handle duplicated middleware', (done) => { + const app = express() app.use(express.json()) app.use(express.json()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -87,7 +87,7 @@ describe('express.json()', function () { .expect(200, '{"user":"tobi"}', done) }) - describe('when JSON is invalid', function () { + describe('when JSON is invalid', () => { before(function () { this.app = createApp() }) @@ -118,9 +118,9 @@ describe('express.json()', function () { }) }) - describe('with limit option', function () { - it('should 413 when over limit with Content-Length', function (done) { - var buf = Buffer.alloc(1024, '.') + describe('with limit option', () => { + it('should 413 when over limit with Content-Length', (done) => { + const buf = Buffer.alloc(1024, '.') request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'application/json') @@ -129,10 +129,10 @@ describe('express.json()', function () { .expect(413, '[entity.too.large] request entity too large', done) }) - it('should 413 when over limit with chunked encoding', function (done) { - var app = createApp({ limit: '1kb' }) - var buf = Buffer.alloc(1024, '.') - var test = request(app).post('/') + it('should 413 when over limit with chunked encoding', (done) => { + const app = createApp({ limit: '1kb' }) + const buf = Buffer.alloc(1024, '.') + const test = request(app).post('/') test.set('Content-Type', 'application/json') test.set('Transfer-Encoding', 'chunked') test.write('{"str":') @@ -140,17 +140,17 @@ describe('express.json()', function () { test.expect(413, done) }) - it('should 413 when inflated body over limit', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should 413 when inflated body over limit', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a040000', 'hex')) test.expect(413, done) }) - it('should accept number of bytes', function (done) { - var buf = Buffer.alloc(1024, '.') + it('should accept number of bytes', (done) => { + const buf = Buffer.alloc(1024, '.') request(createApp({ limit: 1024 })) .post('/') .set('Content-Type', 'application/json') @@ -158,10 +158,10 @@ describe('express.json()', function () { .expect(413, done) }) - it('should not change when options altered', function (done) { - var buf = Buffer.alloc(1024, '.') - var options = { limit: '1kb' } - var app = createApp(options) + it('should not change when options altered', (done) => { + const buf = Buffer.alloc(1024, '.') + const options = { limit: '1kb' } + const app = createApp(options) options.limit = '100kb' @@ -172,10 +172,10 @@ describe('express.json()', function () { .expect(413, done) }) - it('should not hang response', function (done) { - var buf = Buffer.alloc(10240, '.') - var app = createApp({ limit: '8kb' }) - var test = request(app).post('/') + it('should not hang response', (done) => { + const buf = Buffer.alloc(10240, '.') + const app = createApp({ limit: '8kb' }) + const test = request(app).post('/') test.set('Content-Type', 'application/json') test.write(buf) test.write(buf) @@ -183,9 +183,9 @@ describe('express.json()', function () { test.expect(413, done) }) - it('should not error when inflating', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should not error when inflating', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a0400', 'hex')) @@ -193,14 +193,14 @@ describe('express.json()', function () { }) }) - describe('with inflate option', function () { - describe('when false', function () { + describe('with inflate option', () => { + describe('when false', () => { before(function () { this.app = createApp({ inflate: false }) }) it('should not accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) @@ -208,13 +208,13 @@ describe('express.json()', function () { }) }) - describe('when true', function () { + describe('when true', () => { before(function () { this.app = createApp({ inflate: true }) }) it('should accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) @@ -223,8 +223,8 @@ describe('express.json()', function () { }) }) - describe('with strict option', function () { - describe('when undefined', function () { + describe('with strict option', () => { + describe('when undefined', () => { before(function () { this.app = createApp() }) @@ -238,7 +238,7 @@ describe('express.json()', function () { }) }) - describe('when false', function () { + describe('when false', () => { before(function () { this.app = createApp({ strict: false }) }) @@ -252,7 +252,7 @@ describe('express.json()', function () { }) }) - describe('when true', function () { + describe('when true', () => { before(function () { this.app = createApp({ strict: true }) }) @@ -294,8 +294,8 @@ describe('express.json()', function () { }) }) - describe('with type option', function () { - describe('when "application/vnd.api+json"', function () { + describe('with type option', () => { + describe('when "application/vnd.api+json"', () => { before(function () { this.app = createApp({ type: 'application/vnd.api+json' }) }) @@ -317,7 +317,7 @@ describe('express.json()', function () { }) }) - describe('when ["application/json", "application/vnd.api+json"]', function () { + describe('when ["application/json", "application/vnd.api+json"]', () => { before(function () { this.app = createApp({ type: ['application/json', 'application/vnd.api+json'] @@ -349,9 +349,9 @@ describe('express.json()', function () { }) }) - describe('when a function', function () { - it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + describe('when a function', () => { + it('should parse when truthy value returned', (done) => { + const app = createApp({ type: accept }) function accept (req) { return req.headers['content-type'] === 'application/vnd.api+json' @@ -364,20 +364,20 @@ describe('express.json()', function () { .expect(200, '{"user":"tobi"}', done) }) - it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + it('should work without content-type', (done) => { + const app = createApp({ type: accept }) function accept (req) { return true } - var test = request(app).post('/') + const test = request(app).post('/') test.write('{"user":"tobi"}') test.expect(200, '{"user":"tobi"}', done) }) - it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + it('should not invoke without a body', (done) => { + const app = createApp({ type: accept }) function accept (req) { throw new Error('oops!') @@ -390,14 +390,14 @@ describe('express.json()', function () { }) }) - describe('with verify option', function () { - it('should assert value if function', function () { + describe('with verify option', () => { + it('should assert value if function', () => { assert.throws(createApp.bind(null, { verify: 'lol' }), /TypeError: option verify must be function/) }) - it('should error from verify', function (done) { - var app = createApp({ + it('should error from verify', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x5b) throw new Error('no arrays') } @@ -410,11 +410,11 @@ describe('express.json()', function () { .expect(403, '[entity.verify.failed] no arrays', done) }) - it('should allow custom codes', function (done) { - var app = createApp({ + it('should allow custom codes', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] !== 0x5b) return - var err = new Error('no arrays') + const err = new Error('no arrays') err.status = 400 throw err } @@ -427,11 +427,11 @@ describe('express.json()', function () { .expect(400, '[entity.verify.failed] no arrays', done) }) - it('should allow custom type', function (done) { - var app = createApp({ + it('should allow custom type', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] !== 0x5b) return - var err = new Error('no arrays') + const err = new Error('no arrays') err.type = 'foo.bar' throw err } @@ -444,8 +444,8 @@ describe('express.json()', function () { .expect(403, '[foo.bar] no arrays', done) }) - it('should include original body on error object', function (done) { - var app = createApp({ + it('should include original body on error object', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x5b) throw new Error('no arrays') } @@ -459,8 +459,8 @@ describe('express.json()', function () { .expect(403, '["tobi"]', done) }) - it('should allow pass-through', function (done) { - var app = createApp({ + it('should allow pass-through', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x5b) throw new Error('no arrays') } @@ -473,47 +473,47 @@ describe('express.json()', function () { .expect(200, '{"user":"tobi"}', done) }) - it('should work with different charsets', function (done) { - var app = createApp({ + it('should work with different charsets', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x5b) throw new Error('no arrays') } }) - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/json; charset=utf-16') test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex')) test.expect(200, '{"name":"论"}', done) }) - it('should 415 on unknown charset prior to verify', function (done) { - var app = createApp({ + it('should 415 on unknown charset prior to verify', (done) => { + const app = createApp({ verify: function (req, res, buf) { throw new Error('unexpected verify call') } }) - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/json; charset=x-bogus') test.write(Buffer.from('00000000', 'hex')) test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) }) }) - describe('async local storage', function () { + describe('async local storage', () => { before(function () { - var app = express() - var store = { foo: 'bar' } + const app = express() + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) app.use(express.json()) - app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -522,8 +522,8 @@ describe('express.json()', function () { next() }) - app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((err, req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -533,7 +533,7 @@ describe('express.json()', function () { res.send('[' + err.type + '] ' + err.message) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -563,7 +563,7 @@ describe('express.json()', function () { }) it('should persist store when inflated', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) @@ -574,7 +574,7 @@ describe('express.json()', function () { }) it('should persist store when inflate error', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) @@ -604,27 +604,27 @@ describe('express.json()', function () { }) }) - describe('charset', function () { + describe('charset', () => { before(function () { this.app = createApp() }) it('should parse utf-8', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/json; charset=utf-8') test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) test.expect(200, '{"name":"论"}', done) }) it('should parse utf-16', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/json; charset=utf-16') test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex')) test.expect(200, '{"name":"论"}', done) }) it('should parse when content-length != char length', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/json; charset=utf-8') test.set('Content-Length', '13') test.write(Buffer.from('7b2274657374223a22c3a5227d', 'hex')) @@ -632,34 +632,34 @@ describe('express.json()', function () { }) it('should default to utf-8', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/json') test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) test.expect(200, '{"name":"论"}', done) }) it('should fail on unknown charset', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/json; charset=koi8-r') test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex')) test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done) }) }) - describe('encoding', function () { + describe('encoding', () => { before(function () { this.app = createApp({ limit: '1kb' }) }) it('should parse without encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/json') test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) test.expect(200, '{"name":"论"}', done) }) it('should support identity encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'identity') test.set('Content-Type', 'application/json') test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex')) @@ -667,7 +667,7 @@ describe('express.json()', function () { }) it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) @@ -675,7 +675,7 @@ describe('express.json()', function () { }) it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'deflate') test.set('Content-Type', 'application/json') test.write(Buffer.from('789cab56ca4bcc4d55b2527ab16e97522d00274505ac', 'hex')) @@ -683,7 +683,7 @@ describe('express.json()', function () { }) it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'GZIP') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) @@ -691,7 +691,7 @@ describe('express.json()', function () { }) it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'nulls') test.set('Content-Type', 'application/json') test.write(Buffer.from('000000000000', 'hex')) @@ -699,7 +699,7 @@ describe('express.json()', function () { }) it('should 400 on malformed encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')) @@ -708,7 +708,7 @@ describe('express.json()', function () { it('should 413 when inflated value exceeds limit', function (done) { // gzip'd data exceeds 1kb, but deflated below 1kb - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/json') test.write(Buffer.from('1f8b080000000000000bedc1010d000000c2a0f74f6d0f071400000000000000', 'hex')) @@ -720,11 +720,11 @@ describe('express.json()', function () { }) function createApp (options) { - var app = express() + const app = express() app.use(express.json(options)) - app.use(function (err, req, res, next) { + app.use((err, req, res, next) => { // console.log(err) res.status(err.status || 500) res.send(String(req.headers['x-error-property'] @@ -732,7 +732,7 @@ function createApp (options) { : ('[' + err.type + '] ' + err.message))) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) diff --git a/test/express.raw.js b/test/express.raw.js index 5576e225283..488c1122cc6 100644 --- a/test/express.raw.js +++ b/test/express.raw.js @@ -1,13 +1,13 @@ 'use strict' -var assert = require('node:assert') -var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage +const assert = require('node:assert') +const { AsyncLocalStorage } = require('node:async_hooks') -var express = require('..') -var request = require('supertest') -const { Buffer } = require('node:buffer'); +const express = require('../') +const request = require('supertest') +const { Buffer } = require('node:buffer') -describe('express.raw()', function () { +describe('express.raw()', () => { before(function () { this.app = createApp() }) @@ -20,17 +20,17 @@ describe('express.raw()', function () { .expect(200, { buf: '746865207573657220697320746f6269' }, done) }) - it('should 400 when invalid content-length', function (done) { - var app = express() + it('should 400 when invalid content-length', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { req.headers['content-length'] = '20' // bad length next() }) app.use(express.raw()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { if (Buffer.isBuffer(req.body)) { res.json({ buf: req.body.toString('hex') }) } else { @@ -62,13 +62,13 @@ describe('express.raw()', function () { .expect(200, { buf: '' }, done) }) - it('should handle duplicated middleware', function (done) { - var app = express() + it('should handle duplicated middleware', (done) => { + const app = express() app.use(express.raw()) app.use(express.raw()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { if (Buffer.isBuffer(req.body)) { res.json({ buf: req.body.toString('hex') }) } else { @@ -83,62 +83,62 @@ describe('express.raw()', function () { .expect(200, { buf: '746865207573657220697320746f6269' }, done) }) - describe('with limit option', function () { - it('should 413 when over limit with Content-Length', function (done) { - var buf = Buffer.alloc(1028, '.') - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + describe('with limit option', () => { + it('should 413 when over limit with Content-Length', (done) => { + const buf = Buffer.alloc(1028, '.') + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.set('Content-Length', '1028') test.write(buf) test.expect(413, done) }) - it('should 413 when over limit with chunked encoding', function (done) { - var buf = Buffer.alloc(1028, '.') - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should 413 when over limit with chunked encoding', (done) => { + const buf = Buffer.alloc(1028, '.') + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.set('Transfer-Encoding', 'chunked') test.write(buf) test.expect(413, done) }) - it('should 413 when inflated body over limit', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should 413 when inflated body over limit', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', 'hex')) test.expect(413, done) }) - it('should accept number of bytes', function (done) { - var buf = Buffer.alloc(1028, '.') - var app = createApp({ limit: 1024 }) - var test = request(app).post('/') + it('should accept number of bytes', (done) => { + const buf = Buffer.alloc(1028, '.') + const app = createApp({ limit: 1024 }) + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(buf) test.expect(413, done) }) - it('should not change when options altered', function (done) { - var buf = Buffer.alloc(1028, '.') - var options = { limit: '1kb' } - var app = createApp(options) + it('should not change when options altered', (done) => { + const buf = Buffer.alloc(1028, '.') + const options = { limit: '1kb' } + const app = createApp(options) options.limit = '100kb' - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(buf) test.expect(413, done) }) - it('should not hang response', function (done) { - var buf = Buffer.alloc(10240, '.') - var app = createApp({ limit: '8kb' }) - var test = request(app).post('/') + it('should not hang response', (done) => { + const buf = Buffer.alloc(10240, '.') + const app = createApp({ limit: '8kb' }) + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(buf) test.write(buf) @@ -146,9 +146,9 @@ describe('express.raw()', function () { test.expect(413, done) }) - it('should not error when inflating', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should not error when inflating', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a147040400', 'hex')) @@ -156,14 +156,14 @@ describe('express.raw()', function () { }) }) - describe('with inflate option', function () { - describe('when false', function () { + describe('with inflate option', () => { + describe('when false', () => { before(function () { this.app = createApp({ inflate: false }) }) it('should not accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -171,13 +171,13 @@ describe('express.raw()', function () { }) }) - describe('when true', function () { + describe('when true', () => { before(function () { this.app = createApp({ inflate: true }) }) it('should accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -186,28 +186,28 @@ describe('express.raw()', function () { }) }) - describe('with type option', function () { - describe('when "application/vnd+octets"', function () { + describe('with type option', () => { + describe('when "application/vnd+octets"', () => { before(function () { this.app = createApp({ type: 'application/vnd+octets' }) }) it('should parse for custom type', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/vnd+octets') test.write(Buffer.from('000102', 'hex')) test.expect(200, { buf: '000102' }, done) }) it('should ignore standard type', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('000102', 'hex')) test.expect(200, '', done) }) }) - describe('when ["application/octet-stream", "application/vnd+octets"]', function () { + describe('when ["application/octet-stream", "application/vnd+octets"]', () => { before(function () { this.app = createApp({ type: ['application/octet-stream', 'application/vnd+octets'] @@ -215,55 +215,55 @@ describe('express.raw()', function () { }) it('should parse "application/octet-stream"', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('000102', 'hex')) test.expect(200, { buf: '000102' }, done) }) it('should parse "application/vnd+octets"', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/vnd+octets') test.write(Buffer.from('000102', 'hex')) test.expect(200, { buf: '000102' }, done) }) it('should ignore "application/x-foo"', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/x-foo') test.write(Buffer.from('000102', 'hex')) test.expect(200, '', done) }) }) - describe('when a function', function () { - it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + describe('when a function', () => { + it('should parse when truthy value returned', (done) => { + const app = createApp({ type: accept }) function accept (req) { return req.headers['content-type'] === 'application/vnd.octet' } - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/vnd.octet') test.write(Buffer.from('000102', 'hex')) test.expect(200, { buf: '000102' }, done) }) - it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + it('should work without content-type', (done) => { + const app = createApp({ type: accept }) function accept (req) { return true } - var test = request(app).post('/') + const test = request(app).post('/') test.write(Buffer.from('000102', 'hex')) test.expect(200, { buf: '000102' }, done) }) - it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + it('should not invoke without a body', (done) => { + const app = createApp({ type: accept }) function accept (req) { throw new Error('oops!') @@ -276,69 +276,69 @@ describe('express.raw()', function () { }) }) - describe('with verify option', function () { - it('should assert value is function', function () { + describe('with verify option', () => { + it('should assert value is function', () => { assert.throws(createApp.bind(null, { verify: 'lol' }), /TypeError: option verify must be function/) }) - it('should error from verify', function (done) { - var app = createApp({ + it('should error from verify', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x00) throw new Error('no leading null') } }) - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('000102', 'hex')) test.expect(403, '[entity.verify.failed] no leading null', done) }) - it('should allow custom codes', function (done) { - var app = createApp({ + it('should allow custom codes', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] !== 0x00) return - var err = new Error('no leading null') + const err = new Error('no leading null') err.status = 400 throw err } }) - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('000102', 'hex')) test.expect(400, '[entity.verify.failed] no leading null', done) }) - it('should allow pass-through', function (done) { - var app = createApp({ + it('should allow pass-through', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x00) throw new Error('no leading null') } }) - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('0102', 'hex')) test.expect(200, { buf: '0102' }, done) }) }) - describe('async local storage', function () { + describe('async local storage', () => { before(function () { - var app = express() - var store = { foo: 'bar' } + const app = express() + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) app.use(express.raw()) - app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -347,8 +347,8 @@ describe('express.raw()', function () { next() }) - app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((err, req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -358,7 +358,7 @@ describe('express.raw()', function () { res.send('[' + err.type + '] ' + err.message) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { if (Buffer.isBuffer(req.body)) { res.json({ buf: req.body.toString('hex') }) } else { @@ -391,7 +391,7 @@ describe('express.raw()', function () { }) it('should persist store when inflated', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -402,7 +402,7 @@ describe('express.raw()', function () { }) it('should persist store when inflate error', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex')) @@ -422,33 +422,33 @@ describe('express.raw()', function () { }) }) - describe('charset', function () { + describe('charset', () => { before(function () { this.app = createApp() }) it('should ignore charset', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/octet-stream; charset=utf-8') test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) test.expect(200, { buf: '6e616d6520697320e8aeba' }, done) }) }) - describe('encoding', function () { + describe('encoding', () => { before(function () { this.app = createApp({ limit: '10kb' }) }) it('should parse without encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('6e616d653de8aeba', 'hex')) test.expect(200, { buf: '6e616d653de8aeba' }, done) }) it('should support identity encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'identity') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('6e616d653de8aeba', 'hex')) @@ -456,7 +456,7 @@ describe('express.raw()', function () { }) it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -464,7 +464,7 @@ describe('express.raw()', function () { }) it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'deflate') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex')) @@ -472,7 +472,7 @@ describe('express.raw()', function () { }) it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'GZIP') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -480,7 +480,7 @@ describe('express.raw()', function () { }) it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'nulls') test.set('Content-Type', 'application/octet-stream') test.write(Buffer.from('000000000000', 'hex')) @@ -490,18 +490,18 @@ describe('express.raw()', function () { }) function createApp (options) { - var app = express() + const app = express() app.use(express.raw(options)) - app.use(function (err, req, res, next) { + app.use((err, req, res, next) => { res.status(err.status || 500) res.send(String(req.headers['x-error-property'] ? err[req.headers['x-error-property']] : ('[' + err.type + '] ' + err.message))) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { if (Buffer.isBuffer(req.body)) { res.json({ buf: req.body.toString('hex') }) } else { diff --git a/test/express.static.js b/test/express.static.js index a2035631d66..2ec2acb75de 100644 --- a/test/express.static.js +++ b/test/express.static.js @@ -1,29 +1,29 @@ 'use strict' -var assert = require('node:assert') -var express = require('..') -var path = require('node:path') -const { Buffer } = require('node:buffer'); +const assert = require('node:assert') +const express = require('../') +const path = require('node:path') +const { Buffer } = require('node:buffer') -var request = require('supertest') -var utils = require('./support/utils') +const request = require('supertest') +const utils = require('./support/utils') -var fixtures = path.join(__dirname, '/fixtures') -var relative = path.relative(process.cwd(), fixtures) +const fixtures = path.join(__dirname, '/fixtures') +const relative = path.relative(process.cwd(), fixtures) -var skipRelative = ~relative.indexOf('..') || path.resolve(relative) === relative +const skipRelative = ~relative.indexOf('..') || path.resolve(relative) === relative -describe('express.static()', function () { - describe('basic operations', function () { +describe('express.static()', () => { + describe('basic operations', () => { before(function () { this.app = createApp() }) - it('should require root path', function () { + it('should require root path', () => { assert.throws(express.static.bind(), /root path required/) }) - it('should require root path to be string', function () { + it('should require root path to be string', () => { assert.throws(express.static.bind(null, 42), /root path.*string/) }) @@ -101,11 +101,11 @@ describe('express.static()', function () { }) it('should support conditional requests', function (done) { - var app = this.app + const app = this.app request(app) .get('/todo.txt') - .end(function (err, res) { + .end((err, res) => { if (err) throw err request(app) .get('/todo.txt') @@ -134,30 +134,30 @@ describe('express.static()', function () { }) }); - (skipRelative ? describe.skip : describe)('current dir', function () { + (skipRelative ? describe.skip : describe)('current dir', () => { before(function () { this.app = createApp('.') }) it('should be served with "."', function (done) { - var dest = relative.split(path.sep).join('/') + const dest = relative.split(path.sep).join('/') request(this.app) .get('/' + dest + '/todo.txt') .expect(200, '- groceries', done) }) }) - describe('acceptRanges', function () { - describe('when false', function () { - it('should not include Accept-Ranges', function (done) { - request(createApp(fixtures, { 'acceptRanges': false })) + describe('acceptRanges', () => { + describe('when false', () => { + it('should not include Accept-Ranges', (done) => { + request(createApp(fixtures, { acceptRanges: false })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Accept-Ranges')) .expect(200, '123456789', done) }) - it('should ignore Rage request header', function (done) { - request(createApp(fixtures, { 'acceptRanges': false })) + it('should ignore Rage request header', (done) => { + request(createApp(fixtures, { acceptRanges: false })) .get('/nums.txt') .set('Range', 'bytes=0-3') .expect(utils.shouldNotHaveHeader('Accept-Ranges')) @@ -166,16 +166,16 @@ describe('express.static()', function () { }) }) - describe('when true', function () { - it('should include Accept-Ranges', function (done) { - request(createApp(fixtures, { 'acceptRanges': true })) + describe('when true', () => { + it('should include Accept-Ranges', (done) => { + request(createApp(fixtures, { acceptRanges: true })) .get('/nums.txt') .expect('Accept-Ranges', 'bytes') .expect(200, '123456789', done) }) - it('should obey Rage request header', function (done) { - request(createApp(fixtures, { 'acceptRanges': true })) + it('should obey Rage request header', (done) => { + request(createApp(fixtures, { acceptRanges: true })) .get('/nums.txt') .set('Range', 'bytes=0-3') .expect('Accept-Ranges', 'bytes') @@ -185,26 +185,26 @@ describe('express.static()', function () { }) }) - describe('cacheControl', function () { - describe('when false', function () { - it('should not include Cache-Control', function (done) { - request(createApp(fixtures, { 'cacheControl': false })) + describe('cacheControl', () => { + describe('when false', () => { + it('should not include Cache-Control', (done) => { + request(createApp(fixtures, { cacheControl: false })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Cache-Control')) .expect(200, '123456789', done) }) - it('should ignore maxAge', function (done) { - request(createApp(fixtures, { 'cacheControl': false, 'maxAge': 12000 })) + it('should ignore maxAge', (done) => { + request(createApp(fixtures, { cacheControl: false, maxAge: 12000 })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Cache-Control')) .expect(200, '123456789', done) }) }) - describe('when true', function () { - it('should include Cache-Control', function (done) { - request(createApp(fixtures, { 'cacheControl': true })) + describe('when true', () => { + it('should include Cache-Control', (done) => { + request(createApp(fixtures, { cacheControl: true })) .get('/nums.txt') .expect('Cache-Control', 'public, max-age=0') .expect(200, '123456789', done) @@ -212,48 +212,48 @@ describe('express.static()', function () { }) }) - describe('extensions', function () { - it('should be not be enabled by default', function (done) { + describe('extensions', () => { + it('should be not be enabled by default', (done) => { request(createApp(fixtures)) .get('/todo') .expect(404, done) }) - it('should be configurable', function (done) { - request(createApp(fixtures, { 'extensions': 'txt' })) + it('should be configurable', (done) => { + request(createApp(fixtures, { extensions: 'txt' })) .get('/todo') .expect(200, '- groceries', done) }) - it('should support disabling extensions', function (done) { - request(createApp(fixtures, { 'extensions': false })) + it('should support disabling extensions', (done) => { + request(createApp(fixtures, { extensions: false })) .get('/todo') .expect(404, done) }) - it('should support fallbacks', function (done) { - request(createApp(fixtures, { 'extensions': ['htm', 'html', 'txt'] })) + it('should support fallbacks', (done) => { + request(createApp(fixtures, { extensions: ['htm', 'html', 'txt'] })) .get('/todo') .expect(200, '
      • groceries
      • ', done) }) - it('should 404 if nothing found', function (done) { - request(createApp(fixtures, { 'extensions': ['htm', 'html', 'txt'] })) + it('should 404 if nothing found', (done) => { + request(createApp(fixtures, { extensions: ['htm', 'html', 'txt'] })) .get('/bob') .expect(404, done) }) }) - describe('fallthrough', function () { - it('should default to true', function (done) { + describe('fallthrough', () => { + it('should default to true', (done) => { request(createApp()) .get('/does-not-exist') .expect(404, 'Not Found', done) }) - describe('when true', function () { + describe('when true', () => { before(function () { - this.app = createApp(fixtures, { 'fallthrough': true }) + this.app = createApp(fixtures, { fallthrough: true }) }) it('should fall-through when OPTIONS request', function (done) { @@ -274,12 +274,12 @@ describe('express.static()', function () { .expect(404, 'Not Found', done) }) - it('should fall-through when URL too long', function (done) { - var app = express() - var root = fixtures + Array(10000).join('/foobar') + it('should fall-through when URL too long', (done) => { + const app = express() + const root = fixtures + Array(10000).join('/foobar') - app.use(express.static(root, { 'fallthrough': true })) - app.use(function (req, res, next) { + app.use(express.static(root, { fallthrough: true })) + app.use((req, res, next) => { res.sendStatus(404) }) @@ -288,9 +288,9 @@ describe('express.static()', function () { .expect(404, 'Not Found', done) }) - describe('with redirect: true', function () { + describe('with redirect: true', () => { before(function () { - this.app = createApp(fixtures, { 'fallthrough': true, 'redirect': true }) + this.app = createApp(fixtures, { fallthrough: true, redirect: true }) }) it('should fall-through when directory', function (done) { @@ -306,9 +306,9 @@ describe('express.static()', function () { }) }) - describe('with redirect: false', function () { + describe('with redirect: false', () => { before(function () { - this.app = createApp(fixtures, { 'fallthrough': true, 'redirect': false }) + this.app = createApp(fixtures, { fallthrough: true, redirect: false }) }) it('should fall-through when directory', function (done) { @@ -325,9 +325,9 @@ describe('express.static()', function () { }) }) - describe('when false', function () { + describe('when false', () => { before(function () { - this.app = createApp(fixtures, { 'fallthrough': false }) + this.app = createApp(fixtures, { fallthrough: false }) }) it('should 405 when OPTIONS request', function (done) { @@ -349,12 +349,12 @@ describe('express.static()', function () { .expect(403, /ForbiddenError/, done) }) - it('should 404 when URL too long', function (done) { - var app = express() - var root = fixtures + Array(10000).join('/foobar') + it('should 404 when URL too long', (done) => { + const app = express() + const root = fixtures + Array(10000).join('/foobar') - app.use(express.static(root, { 'fallthrough': false })) - app.use(function (req, res, next) { + app.use(express.static(root, { fallthrough: false })) + app.use((req, res, next) => { res.sendStatus(404) }) @@ -363,9 +363,9 @@ describe('express.static()', function () { .expect(404, /ENAMETOOLONG/, done) }) - describe('with redirect: true', function () { + describe('with redirect: true', () => { before(function () { - this.app = createApp(fixtures, { 'fallthrough': false, 'redirect': true }) + this.app = createApp(fixtures, { fallthrough: false, redirect: true }) }) it('should 404 when directory', function (done) { @@ -381,9 +381,9 @@ describe('express.static()', function () { }) }) - describe('with redirect: false', function () { + describe('with redirect: false', () => { before(function () { - this.app = createApp(fixtures, { 'fallthrough': false, 'redirect': false }) + this.app = createApp(fixtures, { fallthrough: false, redirect: false }) }) it('should 404 when directory', function (done) { @@ -401,9 +401,9 @@ describe('express.static()', function () { }) }) - describe('hidden files', function () { + describe('hidden files', () => { before(function () { - this.app = createApp(fixtures, { 'dotfiles': 'allow' }) + this.app = createApp(fixtures, { dotfiles: 'allow' }) }) it('should be served when dotfiles: "allow" is given', function (done) { @@ -415,33 +415,33 @@ describe('express.static()', function () { }) }) - describe('immutable', function () { - it('should default to false', function (done) { + describe('immutable', () => { + it('should default to false', (done) => { request(createApp(fixtures)) .get('/nums.txt') .expect('Cache-Control', 'public, max-age=0', done) }) - it('should set immutable directive in Cache-Control', function (done) { - request(createApp(fixtures, { 'immutable': true, 'maxAge': '1h' })) + it('should set immutable directive in Cache-Control', (done) => { + request(createApp(fixtures, { immutable: true, maxAge: '1h' })) .get('/nums.txt') .expect('Cache-Control', 'public, max-age=3600, immutable', done) }) }) - describe('lastModified', function () { - describe('when false', function () { - it('should not include Last-Modified', function (done) { - request(createApp(fixtures, { 'lastModified': false })) + describe('lastModified', () => { + describe('when false', () => { + it('should not include Last-Modified', (done) => { + request(createApp(fixtures, { lastModified: false })) .get('/nums.txt') .expect(utils.shouldNotHaveHeader('Last-Modified')) .expect(200, '123456789', done) }) }) - describe('when true', function () { - it('should include Last-Modified', function (done) { - request(createApp(fixtures, { 'lastModified': true })) + describe('when true', () => { + it('should include Last-Modified', (done) => { + request(createApp(fixtures, { lastModified: true })) .get('/nums.txt') .expect('Last-Modified', /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/) .expect(200, '123456789', done) @@ -449,26 +449,26 @@ describe('express.static()', function () { }) }) - describe('maxAge', function () { - it('should accept string', function (done) { - request(createApp(fixtures, { 'maxAge': '30d' })) + describe('maxAge', () => { + it('should accept string', (done) => { + request(createApp(fixtures, { maxAge: '30d' })) .get('/todo.txt') .expect('cache-control', 'public, max-age=' + (60 * 60 * 24 * 30)) .expect(200, done) }) - it('should be reasonable when infinite', function (done) { - request(createApp(fixtures, { 'maxAge': Infinity })) + it('should be reasonable when infinite', (done) => { + request(createApp(fixtures, { maxAge: Infinity })) .get('/todo.txt') .expect('cache-control', 'public, max-age=' + (60 * 60 * 24 * 365)) .expect(200, done) }) }) - describe('redirect', function () { + describe('redirect', () => { before(function () { this.app = express() - this.app.use(function (req, res, next) { + this.app.use((req, res, next) => { req.originalUrl = req.url = req.originalUrl.replace(/\/snow(\/|$)/, '/snow \u2603$1') next() @@ -525,9 +525,9 @@ describe('express.static()', function () { .expect(404, done) }) - describe('when false', function () { + describe('when false', () => { before(function () { - this.app = createApp(fixtures, { 'redirect': false }) + this.app = createApp(fixtures, { redirect: false }) }) it('should disable redirect', function (done) { @@ -538,16 +538,18 @@ describe('express.static()', function () { }) }) - describe('setHeaders', function () { + describe('setHeaders', () => { before(function () { this.app = express() - this.app.use(express.static(fixtures, { 'setHeaders': function (res) { - res.setHeader('x-custom', 'set') - } })) + this.app.use(express.static(fixtures, { + setHeaders: function (res) { + res.setHeader('x-custom', 'set') + } + })) }) - it('should reject non-functions', function () { - assert.throws(express.static.bind(null, fixtures, { 'setHeaders': 3 }), /setHeaders.*function/) + it('should reject non-functions', () => { + assert.throws(express.static.bind(null, fixtures, { setHeaders: 3 }), /setHeaders.*function/) }) it('should get called when sending file', function (done) { @@ -572,9 +574,9 @@ describe('express.static()', function () { }) }) - describe('when traversing past root', function () { + describe('when traversing past root', () => { before(function () { - this.app = createApp(fixtures, { 'fallthrough': false }) + this.app = createApp(fixtures, { fallthrough: false }) }) it('should catch urlencoded ../', function (done) { @@ -590,7 +592,7 @@ describe('express.static()', function () { }) }) - describe('when request has "Range" header', function () { + describe('when request has "Range" header', () => { before(function () { this.app = createApp() }) @@ -645,7 +647,7 @@ describe('express.static()', function () { .expect(206, '34', done) }) - describe('when last-byte-pos of the range is greater than current length', function () { + describe('when last-byte-pos of the range is greater than current length', () => { it('is taken to be equal to one less than the current length', function (done) { request(this.app) .get('/nums.txt') @@ -662,7 +664,7 @@ describe('express.static()', function () { }) }) - describe('when the first- byte-pos of the range is greater than the current length', function () { + describe('when the first- byte-pos of the range is greater than the current length', () => { it('should respond with 416', function (done) { request(this.app) .get('/nums.txt') @@ -679,7 +681,7 @@ describe('express.static()', function () { }) }) - describe('when syntactically invalid', function () { + describe('when syntactically invalid', () => { it('should respond with 200 and the entire contents', function (done) { request(this.app) .get('/nums.txt') @@ -689,7 +691,7 @@ describe('express.static()', function () { }) }) - describe('when index at mount point', function () { + describe('when index at mount point', () => { before(function () { this.app = express() this.app.use('/users', express.static(fixtures + '/users')) @@ -703,7 +705,7 @@ describe('express.static()', function () { }) }) - describe('when mounted', function () { + describe('when mounted', () => { before(function () { this.app = express() this.app.use('/static', express.static(fixtures)) @@ -729,7 +731,7 @@ describe('express.static()', function () { // are doing, so this will prevent unseen // regressions around this use-case. // - describe('when mounted "root" as a file', function () { + describe('when mounted "root" as a file', () => { before(function () { this.app = express() this.app.use('/todo.txt', express.static(fixtures + '/todo.txt')) @@ -748,11 +750,11 @@ describe('express.static()', function () { }) }) - describe('when responding non-2xx or 304', function () { - it('should not alter the status', function (done) { - var app = express() + describe('when responding non-2xx or 304', () => { + it('should not alter the status', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { res.status(501) next() }) @@ -764,11 +766,11 @@ describe('express.static()', function () { }) }) - describe('when index file serving disabled', function () { + describe('when index file serving disabled', () => { before(function () { this.app = express() - this.app.use('/static', express.static(fixtures, { 'index': false })) - this.app.use(function (req, res, next) { + this.app.use('/static', express.static(fixtures, { index: false })) + this.app.use((req, res, next) => { res.sendStatus(404) }) }) @@ -802,12 +804,12 @@ describe('express.static()', function () { }) function createApp (dir, options, fn) { - var app = express() - var root = dir || fixtures + const app = express() + const root = dir || fixtures app.use(express.static(root, options)) - app.use(function (req, res, next) { + app.use((req, res, next) => { res.sendStatus(404) }) diff --git a/test/express.text.js b/test/express.text.js index e96cc5efe52..f6cb0d6b633 100644 --- a/test/express.text.js +++ b/test/express.text.js @@ -1,12 +1,12 @@ 'use strict' -var assert = require('node:assert') -var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage -const { Buffer } = require('node:buffer'); -var express = require('..') -var request = require('supertest') +const assert = require('node:assert') +const { AsyncLocalStorage } = require('node:async_hooks') +const { Buffer } = require('node:buffer') +const express = require('../') +const request = require('supertest') -describe('express.text()', function () { +describe('express.text()', () => { before(function () { this.app = createApp() }) @@ -19,17 +19,17 @@ describe('express.text()', function () { .expect(200, '"user is tobi"', done) }) - it('should 400 when invalid content-length', function (done) { - var app = express() + it('should 400 when invalid content-length', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { req.headers['content-length'] = '20' // bad length next() }) app.use(express.text()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -40,7 +40,7 @@ describe('express.text()', function () { .expect(400, /content length/, done) }) - it('should handle Content-Length: 0', function (done) { + it('should handle Content-Length: 0', (done) => { request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'text/plain') @@ -48,7 +48,7 @@ describe('express.text()', function () { .expect(200, '""', done) }) - it('should handle empty message-body', function (done) { + it('should handle empty message-body', (done) => { request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'text/plain') @@ -57,13 +57,13 @@ describe('express.text()', function () { .expect(200, '""', done) }) - it('should handle duplicated middleware', function (done) { - var app = express() + it('should handle duplicated middleware', (done) => { + const app = express() app.use(express.text()) app.use(express.text()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -74,27 +74,27 @@ describe('express.text()', function () { .expect(200, '"user is tobi"', done) }) - describe('with defaultCharset option', function () { - it('should change default charset', function (done) { - var server = createApp({ defaultCharset: 'koi8-r' }) - var test = request(server).post('/') + describe('with defaultCharset option', () => { + it('should change default charset', (done) => { + const server = createApp({ defaultCharset: 'koi8-r' }) + const test = request(server).post('/') test.set('Content-Type', 'text/plain') test.write(Buffer.from('6e616d6520697320cec5d4', 'hex')) test.expect(200, '"name is нет"', done) }) - it('should honor content-type charset', function (done) { - var server = createApp({ defaultCharset: 'koi8-r' }) - var test = request(server).post('/') + it('should honor content-type charset', (done) => { + const server = createApp({ defaultCharset: 'koi8-r' }) + const test = request(server).post('/') test.set('Content-Type', 'text/plain; charset=utf-8') test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) test.expect(200, '"name is 论"', done) }) }) - describe('with limit option', function () { - it('should 413 when over limit with Content-Length', function (done) { - var buf = Buffer.alloc(1028, '.') + describe('with limit option', () => { + it('should 413 when over limit with Content-Length', (done) => { + const buf = Buffer.alloc(1028, '.') request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'text/plain') @@ -103,27 +103,27 @@ describe('express.text()', function () { .expect(413, done) }) - it('should 413 when over limit with chunked encoding', function (done) { - var app = createApp({ limit: '1kb' }) - var buf = Buffer.alloc(1028, '.') - var test = request(app).post('/') + it('should 413 when over limit with chunked encoding', (done) => { + const app = createApp({ limit: '1kb' }) + const buf = Buffer.alloc(1028, '.') + const test = request(app).post('/') test.set('Content-Type', 'text/plain') test.set('Transfer-Encoding', 'chunked') test.write(buf.toString()) test.expect(413, done) }) - it('should 413 when inflated body over limit', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should 413 when inflated body over limit', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', 'hex')) test.expect(413, done) }) - it('should accept number of bytes', function (done) { - var buf = Buffer.alloc(1028, '.') + it('should accept number of bytes', (done) => { + const buf = Buffer.alloc(1028, '.') request(createApp({ limit: 1024 })) .post('/') .set('Content-Type', 'text/plain') @@ -131,10 +131,10 @@ describe('express.text()', function () { .expect(413, done) }) - it('should not change when options altered', function (done) { - var buf = Buffer.alloc(1028, '.') - var options = { limit: '1kb' } - var app = createApp(options) + it('should not change when options altered', (done) => { + const buf = Buffer.alloc(1028, '.') + const options = { limit: '1kb' } + const app = createApp(options) options.limit = '100kb' @@ -145,10 +145,10 @@ describe('express.text()', function () { .expect(413, done) }) - it('should not hang response', function (done) { - var app = createApp({ limit: '8kb' }) - var buf = Buffer.alloc(10240, '.') - var test = request(app).post('/') + it('should not hang response', (done) => { + const app = createApp({ limit: '8kb' }) + const buf = Buffer.alloc(10240, '.') + const test = request(app).post('/') test.set('Content-Type', 'text/plain') test.write(buf) test.write(buf) @@ -156,26 +156,26 @@ describe('express.text()', function () { test.expect(413, done) }) - it('should not error when inflating', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should not error when inflating', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a1470404', 'hex')) - setTimeout(function () { + setTimeout(() => { test.expect(413, done) }, 100) }) }) - describe('with inflate option', function () { - describe('when false', function () { + describe('with inflate option', () => { + describe('when false', () => { before(function () { this.app = createApp({ inflate: false }) }) it('should not accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) @@ -183,13 +183,13 @@ describe('express.text()', function () { }) }) - describe('when true', function () { + describe('when true', () => { before(function () { this.app = createApp({ inflate: true }) }) it('should accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) @@ -198,8 +198,8 @@ describe('express.text()', function () { }) }) - describe('with type option', function () { - describe('when "text/html"', function () { + describe('with type option', () => { + describe('when "text/html"', () => { before(function () { this.app = createApp({ type: 'text/html' }) }) @@ -221,7 +221,7 @@ describe('express.text()', function () { }) }) - describe('when ["text/html", "text/plain"]', function () { + describe('when ["text/html", "text/plain"]', () => { before(function () { this.app = createApp({ type: ['text/html', 'text/plain'] }) }) @@ -251,9 +251,9 @@ describe('express.text()', function () { }) }) - describe('when a function', function () { - it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + describe('when a function', () => { + it('should parse when truthy value returned', (done) => { + const app = createApp({ type: accept }) function accept (req) { return req.headers['content-type'] === 'text/vnd.something' @@ -266,20 +266,20 @@ describe('express.text()', function () { .expect(200, '"user is tobi"', done) }) - it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + it('should work without content-type', (done) => { + const app = createApp({ type: accept }) function accept (req) { return true } - var test = request(app).post('/') + const test = request(app).post('/') test.write('user is tobi') test.expect(200, '"user is tobi"', done) }) - it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + it('should not invoke without a body', (done) => { + const app = createApp({ type: accept }) function accept (req) { throw new Error('oops!') @@ -292,14 +292,14 @@ describe('express.text()', function () { }) }) - describe('with verify option', function () { - it('should assert value is function', function () { + describe('with verify option', () => { + it('should assert value is function', () => { assert.throws(createApp.bind(null, { verify: 'lol' }), /TypeError: option verify must be function/) }) - it('should error from verify', function (done) { - var app = createApp({ + it('should error from verify', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x20) throw new Error('no leading space') } @@ -312,11 +312,11 @@ describe('express.text()', function () { .expect(403, '[entity.verify.failed] no leading space', done) }) - it('should allow custom codes', function (done) { - var app = createApp({ + it('should allow custom codes', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] !== 0x20) return - var err = new Error('no leading space') + const err = new Error('no leading space') err.status = 400 throw err } @@ -329,8 +329,8 @@ describe('express.text()', function () { .expect(400, '[entity.verify.failed] no leading space', done) }) - it('should allow pass-through', function (done) { - var app = createApp({ + it('should allow pass-through', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x20) throw new Error('no leading space') } @@ -343,34 +343,34 @@ describe('express.text()', function () { .expect(200, '"user is tobi"', done) }) - it('should 415 on unknown charset prior to verify', function (done) { - var app = createApp({ + it('should 415 on unknown charset prior to verify', (done) => { + const app = createApp({ verify: function (req, res, buf) { throw new Error('unexpected verify call') } }) - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'text/plain; charset=x-bogus') test.write(Buffer.from('00000000', 'hex')) test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) }) }) - describe('async local storage', function () { + describe('async local storage', () => { before(function () { - var app = express() - var store = { foo: 'bar' } + const app = express() + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) app.use(express.text()) - app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -379,8 +379,8 @@ describe('express.text()', function () { next() }) - app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((err, req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -390,7 +390,7 @@ describe('express.text()', function () { res.send('[' + err.type + '] ' + err.message) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -419,7 +419,7 @@ describe('express.text()', function () { }) it('should persist store when inflated', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) @@ -430,7 +430,7 @@ describe('express.text()', function () { }) it('should persist store when inflate error', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b0000', 'hex')) @@ -450,27 +450,27 @@ describe('express.text()', function () { }) }) - describe('charset', function () { + describe('charset', () => { before(function () { this.app = createApp() }) it('should parse utf-8', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'text/plain; charset=utf-8') test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) test.expect(200, '"name is 论"', done) }) it('should parse codepage charsets', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'text/plain; charset=koi8-r') test.write(Buffer.from('6e616d6520697320cec5d4', 'hex')) test.expect(200, '"name is нет"', done) }) it('should parse when content-length != char length', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'text/plain; charset=utf-8') test.set('Content-Length', '11') test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) @@ -478,34 +478,34 @@ describe('express.text()', function () { }) it('should default to utf-8', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'text/plain') test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) test.expect(200, '"name is 论"', done) }) it('should 415 on unknown charset', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'text/plain; charset=x-bogus') test.write(Buffer.from('00000000', 'hex')) test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) }) }) - describe('encoding', function () { + describe('encoding', () => { before(function () { this.app = createApp({ limit: '10kb' }) }) it('should parse without encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'text/plain') test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) test.expect(200, '"name is 论"', done) }) it('should support identity encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'identity') test.set('Content-Type', 'text/plain') test.write(Buffer.from('6e616d6520697320e8aeba', 'hex')) @@ -513,7 +513,7 @@ describe('express.text()', function () { }) it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) @@ -521,7 +521,7 @@ describe('express.text()', function () { }) it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'deflate') test.set('Content-Type', 'text/plain') test.write(Buffer.from('789ccb4bcc4d55c82c5678b16e17001a6f050e', 'hex')) @@ -529,7 +529,7 @@ describe('express.text()', function () { }) it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'GZIP') test.set('Content-Type', 'text/plain') test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex')) @@ -537,7 +537,7 @@ describe('express.text()', function () { }) it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'nulls') test.set('Content-Type', 'text/plain') test.write(Buffer.from('000000000000', 'hex')) @@ -547,18 +547,18 @@ describe('express.text()', function () { }) function createApp (options) { - var app = express() + const app = express() app.use(express.text(options)) - app.use(function (err, req, res, next) { + app.use((err, req, res, next) => { res.status(err.status || 500) res.send(String(req.headers['x-error-property'] ? err[req.headers['x-error-property']] : ('[' + err.type + '] ' + err.message))) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) diff --git a/test/express.urlencoded.js b/test/express.urlencoded.js index f4acf231989..bd9559bb91e 100644 --- a/test/express.urlencoded.js +++ b/test/express.urlencoded.js @@ -1,13 +1,13 @@ 'use strict' -var assert = require('node:assert') -var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage -const { Buffer } = require('node:buffer'); +const assert = require('node:assert') +const { AsyncLocalStorage } = require('node:async_hooks') +const { Buffer } = require('node:buffer') -var express = require('..') -var request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('express.urlencoded()', function () { +describe('express.urlencoded()', () => { before(function () { this.app = createApp() }) @@ -20,17 +20,17 @@ describe('express.urlencoded()', function () { .expect(200, '{"user":"tobi"}', done) }) - it('should 400 when invalid content-length', function (done) { - var app = express() + it('should 400 when invalid content-length', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { req.headers['content-length'] = '20' // bad length next() }) app.use(express.urlencoded()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -50,7 +50,7 @@ describe('express.urlencoded()', function () { .expect(200, '{}', done) }) - it('should handle empty message-body', function (done) { + it('should handle empty message-body', (done) => { request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -59,13 +59,13 @@ describe('express.urlencoded()', function () { .expect(200, '{}', done) }) - it('should handle duplicated middleware', function (done) { - var app = express() + it('should handle duplicated middleware', (done) => { + const app = express() app.use(express.urlencoded()) app.use(express.urlencoded()) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -84,8 +84,8 @@ describe('express.urlencoded()', function () { .expect(200, '{"user[name][first]":"Tobi"}', done) }) - describe('with extended option', function () { - describe('when false', function () { + describe('with extended option', () => { + describe('when false', () => { before(function () { this.app = createApp({ extended: false }) }) @@ -107,7 +107,7 @@ describe('express.urlencoded()', function () { }) }) - describe('when true', function () { + describe('when true', () => { before(function () { this.app = createApp({ extended: true }) }) @@ -153,9 +153,9 @@ describe('express.urlencoded()', function () { }) it('should parse array index notation with large array', function (done) { - var str = 'f[0]=0' + let str = 'f[0]=0' - for (var i = 1; i < 500; i++) { + for (let i = 1; i < 500; i++) { str += '&f[' + i + ']=' + i.toString(16) } @@ -163,8 +163,8 @@ describe('express.urlencoded()', function () { .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(str) - .expect(function (res) { - var obj = JSON.parse(res.text) + .expect((res) => { + const obj = JSON.parse(res.text) assert.strictEqual(Object.keys(obj).length, 1) assert.strictEqual(Array.isArray(obj.f), true) assert.strictEqual(obj.f.length, 500) @@ -181,9 +181,9 @@ describe('express.urlencoded()', function () { }) it('should parse deep object', function (done) { - var str = 'foo' + let str = 'foo' - for (var i = 0; i < 32; i++) { + for (let i = 0; i < 32; i++) { str += '[p]' } @@ -193,13 +193,13 @@ describe('express.urlencoded()', function () { .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') .send(str) - .expect(function (res) { - var obj = JSON.parse(res.text) + .expect((res) => { + const obj = JSON.parse(res.text) assert.strictEqual(Object.keys(obj).length, 1) assert.strictEqual(typeof obj.foo, 'object') - var depth = 0 - var ref = obj.foo + let depth = 0 + let ref = obj.foo while ((ref = ref.p)) { depth++ } assert.strictEqual(depth, 32) }) @@ -208,14 +208,14 @@ describe('express.urlencoded()', function () { }) }) - describe('with inflate option', function () { - describe('when false', function () { + describe('with inflate option', () => { + describe('when false', () => { before(function () { this.app = createApp({ inflate: false }) }) it('should not accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -223,13 +223,13 @@ describe('express.urlencoded()', function () { }) }) - describe('when true', function () { + describe('when true', () => { before(function () { this.app = createApp({ inflate: true }) }) it('should accept content-encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -238,9 +238,9 @@ describe('express.urlencoded()', function () { }) }) - describe('with limit option', function () { - it('should 413 when over limit with Content-Length', function (done) { - var buf = Buffer.alloc(1024, '.') + describe('with limit option', () => { + it('should 413 when over limit with Content-Length', (done) => { + const buf = Buffer.alloc(1024, '.') request(createApp({ limit: '1kb' })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -249,10 +249,10 @@ describe('express.urlencoded()', function () { .expect(413, done) }) - it('should 413 when over limit with chunked encoding', function (done) { - var app = createApp({ limit: '1kb' }) - var buf = Buffer.alloc(1024, '.') - var test = request(app).post('/') + it('should 413 when over limit with chunked encoding', (done) => { + const app = createApp({ limit: '1kb' }) + const buf = Buffer.alloc(1024, '.') + const test = request(app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded') test.set('Transfer-Encoding', 'chunked') test.write('str=') @@ -260,17 +260,17 @@ describe('express.urlencoded()', function () { test.expect(413, done) }) - it('should 413 when inflated body over limit', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should 413 when inflated body over limit', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f9204040000', 'hex')) test.expect(413, done) }) - it('should accept number of bytes', function (done) { - var buf = Buffer.alloc(1024, '.') + it('should accept number of bytes', (done) => { + const buf = Buffer.alloc(1024, '.') request(createApp({ limit: 1024 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -278,10 +278,10 @@ describe('express.urlencoded()', function () { .expect(413, done) }) - it('should not change when options altered', function (done) { - var buf = Buffer.alloc(1024, '.') - var options = { limit: '1kb' } - var app = createApp(options) + it('should not change when options altered', (done) => { + const buf = Buffer.alloc(1024, '.') + const options = { limit: '1kb' } + const app = createApp(options) options.limit = '100kb' @@ -292,10 +292,10 @@ describe('express.urlencoded()', function () { .expect(413, done) }) - it('should not hang response', function (done) { - var app = createApp({ limit: '8kb' }) - var buf = Buffer.alloc(10240, '.') - var test = request(app).post('/') + it('should not hang response', (done) => { + const app = createApp({ limit: '8kb' }) + const buf = Buffer.alloc(10240, '.') + const test = request(app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(buf) test.write(buf) @@ -303,9 +303,9 @@ describe('express.urlencoded()', function () { test.expect(413, done) }) - it('should not error when inflating', function (done) { - var app = createApp({ limit: '1kb' }) - var test = request(app).post('/') + it('should not error when inflating', (done) => { + const app = createApp({ limit: '1kb' }) + const test = request(app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f92040400', 'hex')) @@ -313,19 +313,19 @@ describe('express.urlencoded()', function () { }) }) - describe('with parameterLimit option', function () { - describe('with extended: false', function () { - it('should reject 0', function () { + describe('with parameterLimit option', () => { + describe('with extended: false', () => { + it('should reject 0', () => { assert.throws(createApp.bind(null, { extended: false, parameterLimit: 0 }), /TypeError: option parameterLimit must be a positive number/) }) - it('should reject string', function () { + it('should reject string', () => { assert.throws(createApp.bind(null, { extended: false, parameterLimit: 'beep' }), /TypeError: option parameterLimit must be a positive number/) }) - it('should 413 if over limit', function (done) { + it('should 413 if over limit', (done) => { request(createApp({ extended: false, parameterLimit: 10 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -333,7 +333,7 @@ describe('express.urlencoded()', function () { .expect(413, '[parameters.too.many] too many parameters', done) }) - it('should work when at the limit', function (done) { + it('should work when at the limit', (done) => { request(createApp({ extended: false, parameterLimit: 10 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -342,7 +342,7 @@ describe('express.urlencoded()', function () { .expect(200, done) }) - it('should work if number is floating point', function (done) { + it('should work if number is floating point', (done) => { request(createApp({ extended: false, parameterLimit: 10.1 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -350,7 +350,7 @@ describe('express.urlencoded()', function () { .expect(413, /too many parameters/, done) }) - it('should work with large limit', function (done) { + it('should work with large limit', (done) => { request(createApp({ extended: false, parameterLimit: 5000 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -359,7 +359,7 @@ describe('express.urlencoded()', function () { .expect(200, done) }) - it('should work with Infinity limit', function (done) { + it('should work with Infinity limit', (done) => { request(createApp({ extended: false, parameterLimit: Infinity })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -369,18 +369,18 @@ describe('express.urlencoded()', function () { }) }) - describe('with extended: true', function () { - it('should reject 0', function () { + describe('with extended: true', () => { + it('should reject 0', () => { assert.throws(createApp.bind(null, { extended: true, parameterLimit: 0 }), /TypeError: option parameterLimit must be a positive number/) }) - it('should reject string', function () { + it('should reject string', () => { assert.throws(createApp.bind(null, { extended: true, parameterLimit: 'beep' }), /TypeError: option parameterLimit must be a positive number/) }) - it('should 413 if over limit', function (done) { + it('should 413 if over limit', (done) => { request(createApp({ extended: true, parameterLimit: 10 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -388,7 +388,7 @@ describe('express.urlencoded()', function () { .expect(413, '[parameters.too.many] too many parameters', done) }) - it('should work when at the limit', function (done) { + it('should work when at the limit', (done) => { request(createApp({ extended: true, parameterLimit: 10 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -397,7 +397,7 @@ describe('express.urlencoded()', function () { .expect(200, done) }) - it('should work if number is floating point', function (done) { + it('should work if number is floating point', (done) => { request(createApp({ extended: true, parameterLimit: 10.1 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -405,7 +405,7 @@ describe('express.urlencoded()', function () { .expect(413, /too many parameters/, done) }) - it('should work with large limit', function (done) { + it('should work with large limit', (done) => { request(createApp({ extended: true, parameterLimit: 5000 })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -414,7 +414,7 @@ describe('express.urlencoded()', function () { .expect(200, done) }) - it('should work with Infinity limit', function (done) { + it('should work with Infinity limit', (done) => { request(createApp({ extended: true, parameterLimit: Infinity })) .post('/') .set('Content-Type', 'application/x-www-form-urlencoded') @@ -425,8 +425,8 @@ describe('express.urlencoded()', function () { }) }) - describe('with type option', function () { - describe('when "application/vnd.x-www-form-urlencoded"', function () { + describe('with type option', () => { + describe('when "application/vnd.x-www-form-urlencoded"', () => { before(function () { this.app = createApp({ type: 'application/vnd.x-www-form-urlencoded' }) }) @@ -448,7 +448,7 @@ describe('express.urlencoded()', function () { }) }) - describe('when ["urlencoded", "application/x-pairs"]', function () { + describe('when ["urlencoded", "application/x-pairs"]', () => { before(function () { this.app = createApp({ type: ['urlencoded', 'application/x-pairs'] @@ -480,9 +480,9 @@ describe('express.urlencoded()', function () { }) }) - describe('when a function', function () { - it('should parse when truthy value returned', function (done) { - var app = createApp({ type: accept }) + describe('when a function', () => { + it('should parse when truthy value returned', (done) => { + const app = createApp({ type: accept }) function accept (req) { return req.headers['content-type'] === 'application/vnd.something' @@ -495,20 +495,20 @@ describe('express.urlencoded()', function () { .expect(200, '{"user":"tobi"}', done) }) - it('should work without content-type', function (done) { - var app = createApp({ type: accept }) + it('should work without content-type', (done) => { + const app = createApp({ type: accept }) function accept (req) { return true } - var test = request(app).post('/') + const test = request(app).post('/') test.write('user=tobi') test.expect(200, '{"user":"tobi"}', done) }) - it('should not invoke without a body', function (done) { - var app = createApp({ type: accept }) + it('should not invoke without a body', (done) => { + const app = createApp({ type: accept }) function accept (req) { throw new Error('oops!') @@ -521,14 +521,14 @@ describe('express.urlencoded()', function () { }) }) - describe('with verify option', function () { - it('should assert value if function', function () { + describe('with verify option', () => { + it('should assert value if function', () => { assert.throws(createApp.bind(null, { verify: 'lol' }), /TypeError: option verify must be function/) }) - it('should error from verify', function (done) { - var app = createApp({ + it('should error from verify', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x20) throw new Error('no leading space') } @@ -541,11 +541,11 @@ describe('express.urlencoded()', function () { .expect(403, '[entity.verify.failed] no leading space', done) }) - it('should allow custom codes', function (done) { - var app = createApp({ + it('should allow custom codes', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] !== 0x20) return - var err = new Error('no leading space') + const err = new Error('no leading space') err.status = 400 throw err } @@ -558,11 +558,11 @@ describe('express.urlencoded()', function () { .expect(400, '[entity.verify.failed] no leading space', done) }) - it('should allow custom type', function (done) { - var app = createApp({ + it('should allow custom type', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] !== 0x20) return - var err = new Error('no leading space') + const err = new Error('no leading space') err.type = 'foo.bar' throw err } @@ -575,8 +575,8 @@ describe('express.urlencoded()', function () { .expect(403, '[foo.bar] no leading space', done) }) - it('should allow pass-through', function (done) { - var app = createApp({ + it('should allow pass-through', (done) => { + const app = createApp({ verify: function (req, res, buf) { if (buf[0] === 0x5b) throw new Error('no arrays') } @@ -589,34 +589,34 @@ describe('express.urlencoded()', function () { .expect(200, '{"user":"tobi"}', done) }) - it('should 415 on unknown charset prior to verify', function (done) { - var app = createApp({ + it('should 415 on unknown charset prior to verify', (done) => { + const app = createApp({ verify: function (req, res, buf) { throw new Error('unexpected verify call') } }) - var test = request(app).post('/') + const test = request(app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded; charset=x-bogus') test.write(Buffer.from('00000000', 'hex')) test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done) }) }) - describe('async local storage', function () { + describe('async local storage', () => { before(function () { - var app = express() - var store = { foo: 'bar' } + const app = express() + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) app.use(express.urlencoded()) - app.use(function (req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -625,8 +625,8 @@ describe('express.urlencoded()', function () { next() }) - app.use(function (err, req, res, next) { - var local = req.asyncLocalStorage.getStore() + app.use((err, req, res, next) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -636,7 +636,7 @@ describe('express.urlencoded()', function () { res.send('[' + err.type + '] ' + err.message) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) @@ -665,7 +665,7 @@ describe('express.urlencoded()', function () { }) it('should persist store when inflated', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -676,7 +676,7 @@ describe('express.urlencoded()', function () { }) it('should persist store when inflate error', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex')) @@ -696,20 +696,20 @@ describe('express.urlencoded()', function () { }) }) - describe('charset', function () { + describe('charset', () => { before(function () { this.app = createApp() }) it('should parse utf-8', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8') test.write(Buffer.from('6e616d653de8aeba', 'hex')) test.expect(200, '{"name":"论"}', done) }) it('should parse when content-length != char length', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8') test.set('Content-Length', '7') test.write(Buffer.from('746573743dc3a5', 'hex')) @@ -717,34 +717,34 @@ describe('express.urlencoded()', function () { }) it('should default to utf-8', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('6e616d653de8aeba', 'hex')) test.expect(200, '{"name":"论"}', done) }) it('should fail on unknown charset', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded; charset=koi8-r') test.write(Buffer.from('6e616d653dcec5d4', 'hex')) test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done) }) }) - describe('encoding', function () { + describe('encoding', () => { before(function () { this.app = createApp({ limit: '10kb' }) }) it('should parse without encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('6e616d653de8aeba', 'hex')) test.expect(200, '{"name":"论"}', done) }) it('should support identity encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'identity') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('6e616d653de8aeba', 'hex')) @@ -752,7 +752,7 @@ describe('express.urlencoded()', function () { }) it('should support gzip encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'gzip') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -760,7 +760,7 @@ describe('express.urlencoded()', function () { }) it('should support deflate encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'deflate') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex')) @@ -768,7 +768,7 @@ describe('express.urlencoded()', function () { }) it('should be case-insensitive', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'GZIP') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex')) @@ -776,7 +776,7 @@ describe('express.urlencoded()', function () { }) it('should 415 on unknown encoding', function (done) { - var test = request(this.app).post('/') + const test = request(this.app).post('/') test.set('Content-Encoding', 'nulls') test.set('Content-Type', 'application/x-www-form-urlencoded') test.write(Buffer.from('000000000000', 'hex')) @@ -786,7 +786,7 @@ describe('express.urlencoded()', function () { }) function createManyParams (count) { - var str = '' + let str = '' if (count === 0) { return str @@ -794,8 +794,8 @@ function createManyParams (count) { str += '0=0' - for (var i = 1; i < count; i++) { - var n = i.toString(36) + for (let i = 1; i < count; i++) { + const n = i.toString(36) str += '&' + n + '=' + n } @@ -803,18 +803,18 @@ function createManyParams (count) { } function createApp (options) { - var app = express() + const app = express() app.use(express.urlencoded(options)) - app.use(function (err, req, res, next) { + app.use((err, req, res, next) => { res.status(err.status || 500) res.send(String(req.headers['x-error-property'] ? err[req.headers['x-error-property']] : ('[' + err.type + '] ' + err.message))) }) - app.post('/', function (req, res) { + app.post('/', (req, res) => { res.json(req.body) }) diff --git a/test/middleware.basic.js b/test/middleware.basic.js index 1f1ed17571a..2270909d247 100644 --- a/test/middleware.basic.js +++ b/test/middleware.basic.js @@ -1,42 +1,42 @@ 'use strict' -var assert = require('node:assert') -var express = require('../'); -var request = require('supertest'); +const assert = require('node:assert') +const express = require('../') +const request = require('supertest') -describe('middleware', function(){ - describe('.next()', function(){ - it('should behave like connect', function(done){ - var app = express() - , calls = []; +describe('middleware', () => { + describe('.next()', () => { + it('should behave like connect', (done) => { + const app = express() + const calls = [] - app.use(function(req, res, next){ - calls.push('one'); - next(); - }); + app.use((req, res, next) => { + calls.push('one') + next() + }) - app.use(function(req, res, next){ - calls.push('two'); - next(); - }); + app.use((req, res, next) => { + calls.push('two') + next() + }) - app.use(function(req, res){ - var buf = ''; - res.setHeader('Content-Type', 'application/json'); - req.setEncoding('utf8'); - req.on('data', function(chunk){ buf += chunk }); - req.on('end', function(){ - res.end(buf); - }); - }); + app.use((req, res) => { + let buf = '' + res.setHeader('Content-Type', 'application/json') + req.setEncoding('utf8') + req.on('data', (chunk) => { buf += chunk }) + req.on('end', () => { + res.end(buf) + }) + }) request(app) - .get('/') - .set('Content-Type', 'application/json') - .send('{"foo":"bar"}') - .expect('Content-Type', 'application/json') - .expect(function () { assert.deepEqual(calls, ['one', 'two']) }) - .expect(200, '{"foo":"bar"}', done) + .get('/') + .set('Content-Type', 'application/json') + .send('{"foo":"bar"}') + .expect('Content-Type', 'application/json') + .expect(() => { assert.deepEqual(calls, ['one', 'two']) }) + .expect(200, '{"foo":"bar"}', done) }) }) }) diff --git a/test/regression.js b/test/regression.js index 4e99b306948..c53173d2ed4 100644 --- a/test/regression.js +++ b/test/regression.js @@ -1,20 +1,20 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('throw after .end()', function(){ - it('should fail gracefully', function(done){ - var app = express(); +describe('throw after .end()', () => { + it('should fail gracefully', (done) => { + const app = express() - app.get('/', function(req, res){ - res.end('yay'); - throw new Error('boom'); - }); + app.get('/', (req, res) => { + res.end('yay') + throw new Error('boom') + }) request(app) - .get('/') - .expect('yay') - .expect(200, done); + .get('/') + .expect('yay') + .expect(200, done) }) }) diff --git a/test/req.accepts.js b/test/req.accepts.js index 2066fb51859..c941d8a3867 100644 --- a/test/req.accepts.js +++ b/test/req.accepts.js @@ -1,125 +1,125 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.accepts(type)', function(){ - it('should return true when Accept is not present', function(done){ - var app = express(); +describe('req', () => { + describe('.accepts(type)', () => { + it('should return true when Accept is not present', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts('json') ? 'yes' : 'no'); - }); + app.use((req, res, next) => { + res.end(req.accepts('json') ? 'yes' : 'no') + }) request(app) - .get('/') - .expect('yes', done); + .get('/') + .expect('yes', done) }) - it('should return true when present', function(done){ - var app = express(); + it('should return true when present', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts('json') ? 'yes' : 'no'); - }); + app.use((req, res, next) => { + res.end(req.accepts('json') ? 'yes' : 'no') + }) request(app) - .get('/') - .set('Accept', 'application/json') - .expect('yes', done); + .get('/') + .set('Accept', 'application/json') + .expect('yes', done) }) - it('should return false otherwise', function(done){ - var app = express(); + it('should return false otherwise', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts('json') ? 'yes' : 'no'); - }); + app.use((req, res, next) => { + res.end(req.accepts('json') ? 'yes' : 'no') + }) request(app) - .get('/') - .set('Accept', 'text/html') - .expect('no', done); + .get('/') + .set('Accept', 'text/html') + .expect('no', done) }) }) - it('should accept an argument list of type names', function(done){ - var app = express(); + it('should accept an argument list of type names', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts('json', 'html')); - }); + app.use((req, res, next) => { + res.end(req.accepts('json', 'html')) + }) request(app) - .get('/') - .set('Accept', 'application/json') - .expect('json', done); + .get('/') + .set('Accept', 'application/json') + .expect('json', done) }) - describe('.accepts(types)', function(){ - it('should return the first when Accept is not present', function(done){ - var app = express(); + describe('.accepts(types)', () => { + it('should return the first when Accept is not present', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts(['json', 'html'])); - }); + app.use((req, res, next) => { + res.end(req.accepts(['json', 'html'])) + }) request(app) - .get('/') - .expect('json', done); + .get('/') + .expect('json', done) }) - it('should return the first acceptable type', function(done){ - var app = express(); + it('should return the first acceptable type', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts(['json', 'html'])); - }); + app.use((req, res, next) => { + res.end(req.accepts(['json', 'html'])) + }) request(app) - .get('/') - .set('Accept', 'text/html') - .expect('html', done); + .get('/') + .set('Accept', 'text/html') + .expect('html', done) }) - it('should return false when no match is made', function(done){ - var app = express(); + it('should return false when no match is made', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts(['text/html', 'application/json']) ? 'yup' : 'nope'); - }); + app.use((req, res, next) => { + res.end(req.accepts(['text/html', 'application/json']) ? 'yup' : 'nope') + }) request(app) - .get('/') - .set('Accept', 'foo/bar, bar/baz') - .expect('nope', done); + .get('/') + .set('Accept', 'foo/bar, bar/baz') + .expect('nope', done) }) - it('should take quality into account', function(done){ - var app = express(); + it('should take quality into account', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts(['text/html', 'application/json'])); - }); + app.use((req, res, next) => { + res.end(req.accepts(['text/html', 'application/json'])) + }) request(app) - .get('/') - .set('Accept', '*/html; q=.5, application/json') - .expect('application/json', done); + .get('/') + .set('Accept', '*/html; q=.5, application/json') + .expect('application/json', done) }) - it('should return the first acceptable type with canonical mime types', function(done){ - var app = express(); + it('should return the first acceptable type with canonical mime types', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.accepts(['application/json', 'text/html'])); - }); + app.use((req, res, next) => { + res.end(req.accepts(['application/json', 'text/html'])) + }) request(app) - .get('/') - .set('Accept', '*/html') - .expect('text/html', done); + .get('/') + .set('Accept', '*/html') + .expect('text/html', done) }) }) }) diff --git a/test/req.acceptsCharsets.js b/test/req.acceptsCharsets.js index 360a9878a78..21c66ae0c1b 100644 --- a/test/req.acceptsCharsets.js +++ b/test/req.acceptsCharsets.js @@ -1,49 +1,49 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.acceptsCharsets(type)', function(){ - describe('when Accept-Charset is not present', function(){ - it('should return true', function(done){ - var app = express(); +describe('req', () => { + describe('.acceptsCharsets(type)', () => { + describe('when Accept-Charset is not present', () => { + it('should return true', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); - }); + app.use((req, res, next) => { + res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no') + }) request(app) - .get('/') - .expect('yes', done); + .get('/') + .expect('yes', done) }) }) - describe('when Accept-Charset is present', function () { - it('should return true', function (done) { - var app = express(); + describe('when Accept-Charset is present', () => { + it('should return true', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); - }); + app.use((req, res, next) => { + res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no') + }) request(app) - .get('/') - .set('Accept-Charset', 'foo, bar, utf-8') - .expect('yes', done); + .get('/') + .set('Accept-Charset', 'foo, bar, utf-8') + .expect('yes', done) }) - it('should return false otherwise', function(done){ - var app = express(); + it('should return false otherwise', (done) => { + const app = express() - app.use(function(req, res, next){ - res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no'); - }); + app.use((req, res, next) => { + res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no') + }) request(app) - .get('/') - .set('Accept-Charset', 'foo, bar') - .expect('no', done); + .get('/') + .set('Accept-Charset', 'foo, bar') + .expect('no', done) }) }) }) diff --git a/test/req.acceptsEncodings.js b/test/req.acceptsEncodings.js index 9f8973cdfb8..0021fa1199d 100644 --- a/test/req.acceptsEncodings.js +++ b/test/req.acceptsEncodings.js @@ -1,14 +1,14 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.acceptsEncodings', function () { - it('should return encoding if accepted', function (done) { - var app = express(); +describe('req', () => { + describe('.acceptsEncodings', () => { + it('should return encoding if accepted', (done) => { + const app = express() - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.send({ gzip: req.acceptsEncodings('gzip'), deflate: req.acceptsEncodings('deflate') @@ -21,10 +21,10 @@ describe('req', function(){ .expect(200, { gzip: 'gzip', deflate: 'deflate' }, done) }) - it('should be false if encoding not accepted', function(done){ - var app = express(); + it('should be false if encoding not accepted', (done) => { + const app = express() - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.send({ bogus: req.acceptsEncodings('bogus') }) diff --git a/test/req.acceptsLanguages.js b/test/req.acceptsLanguages.js index e5629fbc323..7657c88393e 100644 --- a/test/req.acceptsLanguages.js +++ b/test/req.acceptsLanguages.js @@ -1,14 +1,14 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.acceptsLanguages', function(){ - it('should return language if accepted', function (done) { - var app = express(); +describe('req', () => { + describe('.acceptsLanguages', () => { + it('should return language if accepted', (done) => { + const app = express() - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.send({ 'en-us': req.acceptsLanguages('en-us'), en: req.acceptsLanguages('en') @@ -21,10 +21,10 @@ describe('req', function(){ .expect(200, { 'en-us': 'en-us', en: 'en' }, done) }) - it('should be false if language not accepted', function(done){ - var app = express(); + it('should be false if language not accepted', (done) => { + const app = express() - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.send({ es: req.acceptsLanguages('es') }) @@ -36,11 +36,11 @@ describe('req', function(){ .expect(200, { es: false }, done) }) - describe('when Accept-Language is not present', function(){ - it('should always return language', function (done) { - var app = express(); + describe('when Accept-Language is not present', () => { + it('should always return language', (done) => { + const app = express() - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.send({ en: req.acceptsLanguages('en'), es: req.acceptsLanguages('es'), diff --git a/test/req.baseUrl.js b/test/req.baseUrl.js index b70803ea8bb..9c9919f017d 100644 --- a/test/req.baseUrl.js +++ b/test/req.baseUrl.js @@ -1,43 +1,43 @@ 'use strict' -var express = require('..') -var request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.baseUrl', function(){ - it('should be empty for top-level route', function(done){ - var app = express() +describe('req', () => { + describe('.baseUrl', () => { + it('should be empty for top-level route', (done) => { + const app = express() - app.get('/:a', function(req, res){ + app.get('/:a', (req, res) => { res.end(req.baseUrl) }) request(app) - .get('/foo') - .expect(200, '', done) + .get('/foo') + .expect(200, '', done) }) - it('should contain lower path', function(done){ - var app = express() - var sub = express.Router() + it('should contain lower path', (done) => { + const app = express() + const sub = express.Router() - sub.get('/:b', function(req, res){ + sub.get('/:b', (req, res) => { res.end(req.baseUrl) }) app.use('/:a', sub) request(app) - .get('/foo/bar') - .expect(200, '/foo', done); + .get('/foo/bar') + .expect(200, '/foo', done) }) - it('should contain full lower path', function(done){ - var app = express() - var sub1 = express.Router() - var sub2 = express.Router() - var sub3 = express.Router() + it('should contain full lower path', (done) => { + const app = express() + const sub1 = express.Router() + const sub2 = express.Router() + const sub3 = express.Router() - sub3.get('/:d', function(req, res){ + sub3.get('/:d', (req, res) => { res.end(req.baseUrl) }) sub2.use('/:c', sub3) @@ -45,44 +45,44 @@ describe('req', function(){ app.use('/:a', sub1) request(app) - .get('/foo/bar/baz/zed') - .expect(200, '/foo/bar/baz', done); + .get('/foo/bar/baz/zed') + .expect(200, '/foo/bar/baz', done) }) - it('should travel through routers correctly', function(done){ - var urls = [] - var app = express() - var sub1 = express.Router() - var sub2 = express.Router() - var sub3 = express.Router() + it('should travel through routers correctly', (done) => { + const urls = [] + const app = express() + const sub1 = express.Router() + const sub2 = express.Router() + const sub3 = express.Router() - sub3.get('/:d', function(req, res, next){ + sub3.get('/:d', (req, res, next) => { urls.push('0@' + req.baseUrl) next() }) sub2.use('/:c', sub3) - sub1.use('/', function(req, res, next){ + sub1.use('/', (req, res, next) => { urls.push('1@' + req.baseUrl) next() }) sub1.use('/bar', sub2) - sub1.use('/bar', function(req, res, next){ + sub1.use('/bar', (req, res, next) => { urls.push('2@' + req.baseUrl) next() }) - app.use(function(req, res, next){ + app.use((req, res, next) => { urls.push('3@' + req.baseUrl) next() }) app.use('/:a', sub1) - app.use(function(req, res, next){ + app.use((req, res, next) => { urls.push('4@' + req.baseUrl) res.end(urls.join(',')) }) request(app) - .get('/foo/bar/baz/zed') - .expect(200, '3@,1@/foo,0@/foo/bar/baz,2@/foo/bar,4@', done); + .get('/foo/bar/baz/zed') + .expect(200, '3@,1@/foo,0@/foo/bar/baz,2@/foo/bar,4@', done) }) }) }) diff --git a/test/req.fresh.js b/test/req.fresh.js index 3bf6a1f65a7..fa95c659ac6 100644 --- a/test/req.fresh.js +++ b/test/req.fresh.js @@ -1,70 +1,69 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.fresh', function(){ - it('should return true when the resource is not modified', function(done){ - var app = express(); - var etag = '"12345"'; +describe('req', () => { + describe('.fresh', () => { + it('should return true when the resource is not modified', (done) => { + const app = express() + const etag = '"12345"' - app.use(function(req, res){ - res.set('ETag', etag); - res.send(req.fresh); - }); + app.use((req, res) => { + res.set('ETag', etag) + res.send(req.fresh) + }) request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); + .get('/') + .set('If-None-Match', etag) + .expect(304, done) }) - it('should return false when the resource is modified', function(done){ - var app = express(); + it('should return false when the resource is modified', (done) => { + const app = express() - app.use(function(req, res){ - res.set('ETag', '"123"'); - res.send(req.fresh); - }); + app.use((req, res) => { + res.set('ETag', '"123"') + res.send(req.fresh) + }) request(app) - .get('/') - .set('If-None-Match', '"12345"') - .expect(200, 'false', done); + .get('/') + .set('If-None-Match', '"12345"') + .expect(200, 'false', done) }) - it('should return false without response headers', function(done){ - var app = express(); + it('should return false without response headers', (done) => { + const app = express() app.disable('x-powered-by') - app.use(function(req, res){ - res.send(req.fresh); - }); + app.use((req, res) => { + res.send(req.fresh) + }) request(app) - .get('/') - .expect(200, 'false', done); + .get('/') + .expect(200, 'false', done) }) - it('should ignore "If-Modified-Since" when "If-None-Match" is present', function(done) { - var app = express(); + it('should ignore "If-Modified-Since" when "If-None-Match" is present', (done) => { + const app = express() const etag = '"FooBar"' const now = Date.now() app.disable('x-powered-by') - app.use(function(req, res) { + app.use((req, res) => { res.set('Etag', etag) res.set('Last-Modified', new Date(now).toUTCString()) - res.send(req.fresh); - }); + res.send(req.fresh) + }) request(app) .get('/') .set('If-Modified-Since', new Date(now - 1000).toUTCString) .set('If-None-Match', etag) - .expect(304, done); + .expect(304, done) }) - }) }) diff --git a/test/req.get.js b/test/req.get.js index e73d109c84a..ca1b64b33af 100644 --- a/test/req.get.js +++ b/test/req.get.js @@ -1,60 +1,60 @@ 'use strict' -var express = require('../') - , request = require('supertest') - , assert = require('node:assert'); - -describe('req', function(){ - describe('.get(field)', function(){ - it('should return the header field value', function(done){ - var app = express(); - - app.use(function(req, res){ - assert(req.get('Something-Else') === undefined); - res.end(req.get('Content-Type')); - }); +const express = require('../') +const request = require('supertest') +const assert = require('node:assert') + +describe('req', () => { + describe('.get(field)', () => { + it('should return the header field value', (done) => { + const app = express() + + app.use((req, res) => { + assert(req.get('Something-Else') === undefined) + res.end(req.get('Content-Type')) + }) request(app) - .post('/') - .set('Content-Type', 'application/json') - .expect('application/json', done); + .post('/') + .set('Content-Type', 'application/json') + .expect('application/json', done) }) - it('should special-case Referer', function(done){ - var app = express(); + it('should special-case Referer', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.get('Referer')); - }); + app.use((req, res) => { + res.end(req.get('Referer')) + }) request(app) - .post('/') - .set('Referrer', 'http://foobar.com') - .expect('http://foobar.com', done); + .post('/') + .set('Referrer', 'http://foobar.com') + .expect('http://foobar.com', done) }) - it('should throw missing header name', function (done) { - var app = express() + it('should throw missing header name', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.end(req.get()) }) request(app) - .get('/') - .expect(500, /TypeError: name argument is required to req.get/, done) + .get('/') + .expect(500, /TypeError: name argument is required to req.get/, done) }) - it('should throw for non-string header name', function (done) { - var app = express() + it('should throw for non-string header name', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.end(req.get(42)) }) request(app) - .get('/') - .expect(500, /TypeError: name must be a string to req.get/, done) + .get('/') + .expect(500, /TypeError: name must be a string to req.get/, done) }) }) }) diff --git a/test/req.host.js b/test/req.host.js index cdda82eaae3..136f0f7c371 100644 --- a/test/req.host.js +++ b/test/req.host.js @@ -1,155 +1,155 @@ 'use strict' -var express = require('../') - , request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.host', function(){ - it('should return the Host when present', function(done){ - var app = express(); +describe('req', () => { + describe('.host', () => { + it('should return the Host when present', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .post('/') - .set('Host', 'example.com') - .expect('example.com', done); + .post('/') + .set('Host', 'example.com') + .expect('example.com', done) }) - it('should strip port number', function(done){ - var app = express(); + it('should strip port number', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .post('/') - .set('Host', 'example.com:3000') - .expect(200, 'example.com:3000', done); + .post('/') + .set('Host', 'example.com:3000') + .expect(200, 'example.com:3000', done) }) - it('should return undefined otherwise', function(done){ - var app = express(); + it('should return undefined otherwise', (done) => { + const app = express() - app.use(function(req, res){ - req.headers.host = null; - res.end(String(req.host)); - }); + app.use((req, res) => { + req.headers.host = null + res.end(String(req.host)) + }) request(app) - .post('/') - .expect('undefined', done); + .post('/') + .expect('undefined', done) }) - it('should work with IPv6 Host', function(done){ - var app = express(); + it('should work with IPv6 Host', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .post('/') - .set('Host', '[::1]') - .expect('[::1]', done); + .post('/') + .set('Host', '[::1]') + .expect('[::1]', done) }) - it('should work with IPv6 Host and port', function(done){ - var app = express(); + it('should work with IPv6 Host and port', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .post('/') - .set('Host', '[::1]:3000') - .expect(200, '[::1]:3000', done); + .post('/') + .set('Host', '[::1]:3000') + .expect(200, '[::1]:3000', done) }) - describe('when "trust proxy" is enabled', function(){ - it('should respect X-Forwarded-Host', function(done){ - var app = express(); + describe('when "trust proxy" is enabled', () => { + it('should respect X-Forwarded-Host', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('example.com', done); + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('example.com', done) }) - it('should ignore X-Forwarded-Host if socket addr not trusted', function(done){ - var app = express(); + it('should ignore X-Forwarded-Host if socket addr not trusted', (done) => { + const app = express() - app.set('trust proxy', '10.0.0.1'); + app.set('trust proxy', '10.0.0.1') - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('localhost', done); + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('localhost', done) }) - it('should default to Host', function(done){ - var app = express(); + it('should default to Host', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .get('/') - .set('Host', 'example.com') - .expect('example.com', done); + .get('/') + .set('Host', 'example.com') + .expect('example.com', done) }) - describe('when trusting hop count', function () { - it('should respect X-Forwarded-Host', function (done) { - var app = express(); + describe('when trusting hop count', () => { + it('should respect X-Forwarded-Host', (done) => { + const app = express() - app.set('trust proxy', 1); + app.set('trust proxy', 1) - app.use(function (req, res) { - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('example.com', done); + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('example.com', done) }) }) }) - describe('when "trust proxy" is disabled', function(){ - it('should ignore X-Forwarded-Host', function(done){ - var app = express(); + describe('when "trust proxy" is disabled', () => { + it('should ignore X-Forwarded-Host', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.host); - }); + app.use((req, res) => { + res.end(req.host) + }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'evil') - .expect('localhost', done); + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'evil') + .expect('localhost', done) }) }) }) diff --git a/test/req.hostname.js b/test/req.hostname.js index b3716b566ae..4b12e951fb9 100644 --- a/test/req.hostname.js +++ b/test/req.hostname.js @@ -1,187 +1,187 @@ 'use strict' -var express = require('../') - , request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.hostname', function(){ - it('should return the Host when present', function(done){ - var app = express(); +describe('req', () => { + describe('.hostname', () => { + it('should return the Host when present', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .post('/') - .set('Host', 'example.com') - .expect('example.com', done); + .post('/') + .set('Host', 'example.com') + .expect('example.com', done) }) - it('should strip port number', function(done){ - var app = express(); + it('should strip port number', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .post('/') - .set('Host', 'example.com:3000') - .expect('example.com', done); + .post('/') + .set('Host', 'example.com:3000') + .expect('example.com', done) }) - it('should return undefined otherwise', function(done){ - var app = express(); + it('should return undefined otherwise', (done) => { + const app = express() - app.use(function(req, res){ - req.headers.host = null; - res.end(String(req.hostname)); - }); + app.use((req, res) => { + req.headers.host = null + res.end(String(req.hostname)) + }) request(app) - .post('/') - .expect('undefined', done); + .post('/') + .expect('undefined', done) }) - it('should work with IPv6 Host', function(done){ - var app = express(); + it('should work with IPv6 Host', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .post('/') - .set('Host', '[::1]') - .expect('[::1]', done); + .post('/') + .set('Host', '[::1]') + .expect('[::1]', done) }) - it('should work with IPv6 Host and port', function(done){ - var app = express(); + it('should work with IPv6 Host and port', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .post('/') - .set('Host', '[::1]:3000') - .expect('[::1]', done); + .post('/') + .set('Host', '[::1]:3000') + .expect('[::1]', done) }) - describe('when "trust proxy" is enabled', function(){ - it('should respect X-Forwarded-Host', function(done){ - var app = express(); + describe('when "trust proxy" is enabled', () => { + it('should respect X-Forwarded-Host', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com:3000') - .expect('example.com', done); + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com:3000') + .expect('example.com', done) }) - it('should ignore X-Forwarded-Host if socket addr not trusted', function(done){ - var app = express(); + it('should ignore X-Forwarded-Host if socket addr not trusted', (done) => { + const app = express() - app.set('trust proxy', '10.0.0.1'); + app.set('trust proxy', '10.0.0.1') - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com') - .expect('localhost', done); + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com') + .expect('localhost', done) }) - it('should default to Host', function(done){ - var app = express(); + it('should default to Host', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .get('/') - .set('Host', 'example.com') - .expect('example.com', done); + .get('/') + .set('Host', 'example.com') + .expect('example.com', done) }) - describe('when multiple X-Forwarded-Host', function () { - it('should use the first value', function (done) { - var app = express() + describe('when multiple X-Forwarded-Host', () => { + it('should use the first value', (done) => { + const app = express() app.enable('trust proxy') - app.use(function (req, res) { + app.use((req, res) => { res.send(req.hostname) }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com, foobar.com') - .expect(200, 'example.com', done) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com, foobar.com') + .expect(200, 'example.com', done) }) - it('should remove OWS around comma', function (done) { - var app = express() + it('should remove OWS around comma', (done) => { + const app = express() app.enable('trust proxy') - app.use(function (req, res) { + app.use((req, res) => { res.send(req.hostname) }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com , foobar.com') - .expect(200, 'example.com', done) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com , foobar.com') + .expect(200, 'example.com', done) }) - it('should strip port number', function (done) { - var app = express() + it('should strip port number', (done) => { + const app = express() app.enable('trust proxy') - app.use(function (req, res) { + app.use((req, res) => { res.send(req.hostname) }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'example.com:8080 , foobar.com:8888') - .expect(200, 'example.com', done) + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'example.com:8080 , foobar.com:8888') + .expect(200, 'example.com', done) }) }) }) - describe('when "trust proxy" is disabled', function(){ - it('should ignore X-Forwarded-Host', function(done){ - var app = express(); + describe('when "trust proxy" is disabled', () => { + it('should ignore X-Forwarded-Host', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.hostname); - }); + app.use((req, res) => { + res.end(req.hostname) + }) request(app) - .get('/') - .set('Host', 'localhost') - .set('X-Forwarded-Host', 'evil') - .expect('localhost', done); + .get('/') + .set('Host', 'localhost') + .set('X-Forwarded-Host', 'evil') + .expect('localhost', done) }) }) }) diff --git a/test/req.ip.js b/test/req.ip.js index 6bb3c5ac52f..067233bcae2 100644 --- a/test/req.ip.js +++ b/test/req.ip.js @@ -1,48 +1,48 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.ip', function(){ - describe('when X-Forwarded-For is present', function(){ - describe('when "trust proxy" is enabled', function(){ - it('should return the client addr', function(done){ - var app = express(); +describe('req', () => { + describe('.ip', () => { + describe('when X-Forwarded-For is present', () => { + describe('when "trust proxy" is enabled', () => { + it('should return the client addr', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res, next){ - res.send(req.ip); - }); + app.use((req, res, next) => { + res.send(req.ip) + }) request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('client', done); + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('client', done) }) - it('should return the addr after trusted proxy based on count', function (done) { - var app = express(); + it('should return the addr after trusted proxy based on count', (done) => { + const app = express() - app.set('trust proxy', 2); + app.set('trust proxy', 2) - app.use(function(req, res, next){ - res.send(req.ip); - }); + app.use((req, res, next) => { + res.send(req.ip) + }) request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('p1', done); + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('p1', done) }) - it('should return the addr after trusted proxy based on list', function (done) { - var app = express() + it('should return the addr after trusted proxy based on list', (done) => { + const app = express() app.set('trust proxy', '10.0.0.1, 10.0.0.2, 127.0.0.1, ::1') - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.send(req.ip) }) @@ -52,50 +52,50 @@ describe('req', function(){ .expect('10.0.0.3', done) }) - it('should return the addr after trusted proxy, from sub app', function (done) { - var app = express(); - var sub = express(); + it('should return the addr after trusted proxy, from sub app', (done) => { + const app = express() + const sub = express() - app.set('trust proxy', 2); - app.use(sub); + app.set('trust proxy', 2) + app.use(sub) - sub.use(function (req, res, next) { - res.send(req.ip); - }); + sub.use((req, res, next) => { + res.send(req.ip) + }) request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect(200, 'p1', done); + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect(200, 'p1', done) }) }) - describe('when "trust proxy" is disabled', function(){ - it('should return the remote address', function(done){ - var app = express(); + describe('when "trust proxy" is disabled', () => { + it('should return the remote address', (done) => { + const app = express() - app.use(function(req, res, next){ - res.send(req.ip); - }); + app.use((req, res, next) => { + res.send(req.ip) + }) - var test = request(app).get('/') + const test = request(app).get('/') test.set('X-Forwarded-For', 'client, p1, p2') - test.expect(200, getExpectedClientAddress(test._server), done); + test.expect(200, getExpectedClientAddress(test._server), done) }) }) }) - describe('when X-Forwarded-For is not present', function(){ - it('should return the remote address', function(done){ - var app = express(); + describe('when X-Forwarded-For is not present', () => { + it('should return the remote address', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res, next){ - res.send(req.ip); - }); + app.use((req, res, next) => { + res.send(req.ip) + }) - var test = request(app).get('/') + const test = request(app).get('/') test.expect(200, getExpectedClientAddress(test._server), done) }) }) @@ -106,8 +106,8 @@ describe('req', function(){ * Get the local client address depending on AF_NET of server */ -function getExpectedClientAddress(server) { +function getExpectedClientAddress (server) { return server.address().address === '::' ? '::ffff:127.0.0.1' - : '127.0.0.1'; + : '127.0.0.1' } diff --git a/test/req.ips.js b/test/req.ips.js index 2f9a0736ea3..5a1fd4bed9f 100644 --- a/test/req.ips.js +++ b/test/req.ips.js @@ -1,70 +1,70 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.ips', function(){ - describe('when X-Forwarded-For is present', function(){ - describe('when "trust proxy" is enabled', function(){ - it('should return an array of the specified addresses', function(done){ - var app = express(); +describe('req', () => { + describe('.ips', () => { + describe('when X-Forwarded-For is present', () => { + describe('when "trust proxy" is enabled', () => { + it('should return an array of the specified addresses', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res, next){ - res.send(req.ips); - }); + app.use((req, res, next) => { + res.send(req.ips) + }) request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('["client","p1","p2"]', done); + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('["client","p1","p2"]', done) }) - it('should stop at first untrusted', function(done){ - var app = express(); + it('should stop at first untrusted', (done) => { + const app = express() - app.set('trust proxy', 2); + app.set('trust proxy', 2) - app.use(function(req, res, next){ - res.send(req.ips); - }); + app.use((req, res, next) => { + res.send(req.ips) + }) request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('["p1","p2"]', done); + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('["p1","p2"]', done) }) }) - describe('when "trust proxy" is disabled', function(){ - it('should return an empty array', function(done){ - var app = express(); + describe('when "trust proxy" is disabled', () => { + it('should return an empty array', (done) => { + const app = express() - app.use(function(req, res, next){ - res.send(req.ips); - }); + app.use((req, res, next) => { + res.send(req.ips) + }) request(app) - .get('/') - .set('X-Forwarded-For', 'client, p1, p2') - .expect('[]', done); + .get('/') + .set('X-Forwarded-For', 'client, p1, p2') + .expect('[]', done) }) }) }) - describe('when X-Forwarded-For is not present', function(){ - it('should return []', function(done){ - var app = express(); + describe('when X-Forwarded-For is not present', () => { + it('should return []', (done) => { + const app = express() - app.use(function(req, res, next){ - res.send(req.ips); - }); + app.use((req, res, next) => { + res.send(req.ips) + }) request(app) - .get('/') - .expect('[]', done); + .get('/') + .expect('[]', done) }) }) }) diff --git a/test/req.is.js b/test/req.is.js index c5904dd600a..a1573a385db 100644 --- a/test/req.is.js +++ b/test/req.is.js @@ -1,169 +1,169 @@ 'use strict' -var express = require('..') -var request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('req.is()', function () { - describe('when given a mime type', function () { - it('should return the type when matching', function (done) { - var app = express() +describe('req.is()', () => { + describe('when given a mime type', () => { + it('should return the type when matching', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('application/json')) }) request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"application/json"', done) + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"application/json"', done) }) - it('should return false when not matching', function (done) { - var app = express() + it('should return false when not matching', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('image/jpeg')) }) request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, 'false', done) + .post('/') + .type('application/json') + .send('{}') + .expect(200, 'false', done) }) - it('should ignore charset', function (done) { - var app = express() + it('should ignore charset', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('application/json')) }) request(app) - .post('/') - .type('application/json; charset=UTF-8') - .send('{}') - .expect(200, '"application/json"', done) + .post('/') + .type('application/json; charset=UTF-8') + .send('{}') + .expect(200, '"application/json"', done) }) }) - describe('when content-type is not present', function(){ - it('should return false', function (done) { - var app = express() + describe('when content-type is not present', () => { + it('should return false', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('application/json')) }) request(app) - .post('/') - .send('{}') - .expect(200, 'false', done) + .post('/') + .send('{}') + .expect(200, 'false', done) }) }) - describe('when given an extension', function(){ - it('should lookup the mime type', function (done) { - var app = express() + describe('when given an extension', () => { + it('should lookup the mime type', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('json')) }) request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"json"', done) + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"json"', done) }) }) - describe('when given */subtype', function(){ - it('should return the full type when matching', function (done) { - var app = express() + describe('when given */subtype', () => { + it('should return the full type when matching', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('*/json')) }) request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"application/json"', done) + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"application/json"', done) }) - it('should return false when not matching', function (done) { - var app = express() + it('should return false when not matching', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('*/html')) }) request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, 'false', done) + .post('/') + .type('application/json') + .send('{}') + .expect(200, 'false', done) }) - it('should ignore charset', function (done) { - var app = express() + it('should ignore charset', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('*/json')) }) request(app) - .post('/') - .type('application/json; charset=UTF-8') - .send('{}') - .expect(200, '"application/json"', done) + .post('/') + .type('application/json; charset=UTF-8') + .send('{}') + .expect(200, '"application/json"', done) }) }) - describe('when given type/*', function(){ - it('should return the full type when matching', function (done) { - var app = express() + describe('when given type/*', () => { + it('should return the full type when matching', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('application/*')) }) request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, '"application/json"', done) + .post('/') + .type('application/json') + .send('{}') + .expect(200, '"application/json"', done) }) - it('should return false when not matching', function (done) { - var app = express() + it('should return false when not matching', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('text/*')) }) request(app) - .post('/') - .type('application/json') - .send('{}') - .expect(200, 'false', done) + .post('/') + .type('application/json') + .send('{}') + .expect(200, 'false', done) }) - it('should ignore charset', function (done) { - var app = express() + it('should ignore charset', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.is('application/*')) }) request(app) - .post('/') - .type('application/json; charset=UTF-8') - .send('{}') - .expect(200, '"application/json"', done) + .post('/') + .type('application/json; charset=UTF-8') + .send('{}') + .expect(200, '"application/json"', done) }) }) }) diff --git a/test/req.path.js b/test/req.path.js index 3ff6177c74e..21f4d5bb1e1 100644 --- a/test/req.path.js +++ b/test/req.path.js @@ -1,20 +1,20 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.path', function(){ - it('should return the parsed pathname', function(done){ - var app = express(); +describe('req', () => { + describe('.path', () => { + it('should return the parsed pathname', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.path); - }); + app.use((req, res) => { + res.end(req.path) + }) request(app) - .get('/login?redirect=/post/1/comments') - .expect('/login', done); + .get('/login?redirect=/post/1/comments') + .expect('/login', done) }) }) }) diff --git a/test/req.protocol.js b/test/req.protocol.js index def82eda922..a5d52a7053d 100644 --- a/test/req.protocol.js +++ b/test/req.protocol.js @@ -1,112 +1,112 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.protocol', function(){ - it('should return the protocol string', function(done){ - var app = express(); +describe('req', () => { + describe('.protocol', () => { + it('should return the protocol string', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.protocol); - }); + app.use((req, res) => { + res.end(req.protocol) + }) request(app) - .get('/') - .expect('http', done); + .get('/') + .expect('http', done) }) - describe('when "trust proxy" is enabled', function(){ - it('should respect X-Forwarded-Proto', function(done){ - var app = express(); + describe('when "trust proxy" is enabled', () => { + it('should respect X-Forwarded-Proto', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res){ - res.end(req.protocol); - }); + app.use((req, res) => { + res.end(req.protocol) + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('https', done); + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('https', done) }) - it('should default to the socket addr if X-Forwarded-Proto not present', function(done){ - var app = express(); + it('should default to the socket addr if X-Forwarded-Proto not present', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res){ - req.socket.encrypted = true; - res.end(req.protocol); - }); + app.use((req, res) => { + req.socket.encrypted = true + res.end(req.protocol) + }) request(app) - .get('/') - .expect('https', done); + .get('/') + .expect('https', done) }) - it('should ignore X-Forwarded-Proto if socket addr not trusted', function(done){ - var app = express(); + it('should ignore X-Forwarded-Proto if socket addr not trusted', (done) => { + const app = express() - app.set('trust proxy', '10.0.0.1'); + app.set('trust proxy', '10.0.0.1') - app.use(function(req, res){ - res.end(req.protocol); - }); + app.use((req, res) => { + res.end(req.protocol) + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('http', done); + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('http', done) }) - it('should default to http', function(done){ - var app = express(); + it('should default to http', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.use(function(req, res){ - res.end(req.protocol); - }); + app.use((req, res) => { + res.end(req.protocol) + }) request(app) - .get('/') - .expect('http', done); + .get('/') + .expect('http', done) }) - describe('when trusting hop count', function () { - it('should respect X-Forwarded-Proto', function (done) { - var app = express(); + describe('when trusting hop count', () => { + it('should respect X-Forwarded-Proto', (done) => { + const app = express() - app.set('trust proxy', 1); + app.set('trust proxy', 1) - app.use(function (req, res) { - res.end(req.protocol); - }); + app.use((req, res) => { + res.end(req.protocol) + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('https', done); + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('https', done) }) }) }) - describe('when "trust proxy" is disabled', function(){ - it('should ignore X-Forwarded-Proto', function(done){ - var app = express(); + describe('when "trust proxy" is disabled', () => { + it('should ignore X-Forwarded-Proto', (done) => { + const app = express() - app.use(function(req, res){ - res.end(req.protocol); - }); + app.use((req, res) => { + res.end(req.protocol) + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('http', done); + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('http', done) }) }) }) diff --git a/test/req.query.js b/test/req.query.js index c0d3c8376e9..1a27bb5dc1d 100644 --- a/test/req.query.js +++ b/test/req.query.js @@ -1,106 +1,104 @@ 'use strict' -var assert = require('node:assert') -var express = require('../') - , request = require('supertest'); +const assert = require('node:assert') +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.query', function(){ - it('should default to {}', function(done){ - var app = createApp(); +describe('req', () => { + describe('.query', () => { + it('should default to {}', (done) => { + const app = createApp() request(app) - .get('/') - .expect(200, '{}', done); - }); + .get('/') + .expect(200, '{}', done) + }) - it('should default to parse simple keys', function (done) { - var app = createApp(); + it('should default to parse simple keys', (done) => { + const app = createApp() request(app) - .get('/?user[name]=tj') - .expect(200, '{"user[name]":"tj"}', done); - }); + .get('/?user[name]=tj') + .expect(200, '{"user[name]":"tj"}', done) + }) - describe('when "query parser" is extended', function () { - it('should parse complex keys', function (done) { - var app = createApp('extended'); + describe('when "query parser" is extended', () => { + it('should parse complex keys', (done) => { + const app = createApp('extended') request(app) - .get('/?foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!') - .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done); - }); + .get('/?foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!') + .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done) + }) - it('should parse parameters with dots', function (done) { - var app = createApp('extended'); + it('should parse parameters with dots', (done) => { + const app = createApp('extended') request(app) - .get('/?user.name=tj') - .expect(200, '{"user.name":"tj"}', done); - }); - }); + .get('/?user.name=tj') + .expect(200, '{"user.name":"tj"}', done) + }) + }) - describe('when "query parser" is simple', function () { - it('should not parse complex keys', function (done) { - var app = createApp('simple'); + describe('when "query parser" is simple', () => { + it('should not parse complex keys', (done) => { + const app = createApp('simple') request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{"user[name]":"tj"}', done); - }); - }); + .get('/?user%5Bname%5D=tj') + .expect(200, '{"user[name]":"tj"}', done) + }) + }) - describe('when "query parser" is a function', function () { - it('should parse using function', function (done) { - var app = createApp(function (str) { - return {'length': (str || '').length}; - }); + describe('when "query parser" is a function', () => { + it('should parse using function', (done) => { + const app = createApp((str) => ({ length: (str || '').length })) request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{"length":17}', done); - }); - }); + .get('/?user%5Bname%5D=tj') + .expect(200, '{"length":17}', done) + }) + }) - describe('when "query parser" disabled', function () { - it('should not parse query', function (done) { - var app = createApp(false); + describe('when "query parser" disabled', () => { + it('should not parse query', (done) => { + const app = createApp(false) request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{}', done); - }); - }); + .get('/?user%5Bname%5D=tj') + .expect(200, '{}', done) + }) + }) - describe('when "query parser" enabled', function () { - it('should not parse complex keys', function (done) { - var app = createApp(true); + describe('when "query parser" enabled', () => { + it('should not parse complex keys', (done) => { + const app = createApp(true) request(app) - .get('/?user%5Bname%5D=tj') - .expect(200, '{"user[name]":"tj"}', done); - }); - }); + .get('/?user%5Bname%5D=tj') + .expect(200, '{"user[name]":"tj"}', done) + }) + }) - describe('when "query parser" an unknown value', function () { - it('should throw', function () { + describe('when "query parser" an unknown value', () => { + it('should throw', () => { assert.throws(createApp.bind(null, 'bogus'), /unknown value.*query parser/) - }); - }); + }) + }) }) }) -function createApp(setting) { - var app = express(); +function createApp (setting) { + const app = express() if (setting !== undefined) { - app.set('query parser', setting); + app.set('query parser', setting) } - app.use(function (req, res) { - res.send(req.query); - }); + app.use((req, res) => { + res.send(req.query) + }) - return app; + return app } diff --git a/test/req.range.js b/test/req.range.js index 111441736eb..50a3c9f5ea1 100644 --- a/test/req.range.js +++ b/test/req.range.js @@ -1,103 +1,103 @@ 'use strict' -var express = require('..'); -var request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.range(size)', function(){ - it('should return parsed ranges', function (done) { - var app = express() +describe('req', () => { + describe('.range(size)', () => { + it('should return parsed ranges', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.range(120)) }) request(app) - .get('/') - .set('Range', 'bytes=0-50,51-100') - .expect(200, '[{"start":0,"end":50},{"start":51,"end":100}]', done) + .get('/') + .set('Range', 'bytes=0-50,51-100') + .expect(200, '[{"start":0,"end":50},{"start":51,"end":100}]', done) }) - it('should cap to the given size', function (done) { - var app = express() + it('should cap to the given size', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.range(75)) }) request(app) - .get('/') - .set('Range', 'bytes=0-100') - .expect(200, '[{"start":0,"end":74}]', done) + .get('/') + .set('Range', 'bytes=0-100') + .expect(200, '[{"start":0,"end":74}]', done) }) - it('should cap to the given size when open-ended', function (done) { - var app = express() + it('should cap to the given size when open-ended', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.range(75)) }) request(app) - .get('/') - .set('Range', 'bytes=0-') - .expect(200, '[{"start":0,"end":74}]', done) + .get('/') + .set('Range', 'bytes=0-') + .expect(200, '[{"start":0,"end":74}]', done) }) - it('should have a .type', function (done) { - var app = express() + it('should have a .type', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.range(120).type) }) request(app) - .get('/') - .set('Range', 'bytes=0-100') - .expect(200, '"bytes"', done) + .get('/') + .set('Range', 'bytes=0-100') + .expect(200, '"bytes"', done) }) - it('should accept any type', function (done) { - var app = express() + it('should accept any type', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.range(120).type) }) request(app) - .get('/') - .set('Range', 'users=0-2') - .expect(200, '"users"', done) + .get('/') + .set('Range', 'users=0-2') + .expect(200, '"users"', done) }) - it('should return undefined if no range', function (done) { - var app = express() + it('should return undefined if no range', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.send(String(req.range(120))) }) request(app) - .get('/') - .expect(200, 'undefined', done) + .get('/') + .expect(200, 'undefined', done) }) }) - describe('.range(size, options)', function(){ - describe('with "combine: true" option', function(){ - it('should return combined ranges', function (done) { - var app = express() + describe('.range(size, options)', () => { + describe('with "combine: true" option', () => { + it('should return combined ranges', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.json(req.range(120, { combine: true })) }) request(app) - .get('/') - .set('Range', 'bytes=0-50,51-100') - .expect(200, '[{"start":0,"end":100}]', done) + .get('/') + .set('Range', 'bytes=0-50,51-100') + .expect(200, '[{"start":0,"end":100}]', done) }) }) }) diff --git a/test/req.route.js b/test/req.route.js index 9bd7ed923b4..c7dbd7cf992 100644 --- a/test/req.route.js +++ b/test/req.route.js @@ -1,22 +1,22 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.route', function(){ - it('should be the executed Route', function(done){ - var app = express(); +describe('req', () => { + describe('.route', () => { + it('should be the executed Route', (done) => { + const app = express() - app.get('/user/:id{/:op}', function(req, res, next){ + app.get('/user/:id{/:op}', (req, res, next) => { res.header('path-1', req.route.path) - next(); - }); + next() + }) - app.get('/user/:id/edit', function(req, res){ + app.get('/user/:id/edit', (req, res) => { res.header('path-2', req.route.path) - res.end(); - }); + res.end() + }) request(app) .get('/user/12/edit') diff --git a/test/req.secure.js b/test/req.secure.js index 0097ed6136e..c8393b65725 100644 --- a/test/req.secure.js +++ b/test/req.secure.js @@ -1,99 +1,99 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.secure', function(){ - describe('when X-Forwarded-Proto is missing', function(){ - it('should return false when http', function(done){ - var app = express(); +describe('req', () => { + describe('.secure', () => { + describe('when X-Forwarded-Proto is missing', () => { + it('should return false when http', (done) => { + const app = express() - app.get('/', function(req, res){ - res.send(req.secure ? 'yes' : 'no'); - }); + app.get('/', (req, res) => { + res.send(req.secure ? 'yes' : 'no') + }) request(app) - .get('/') - .expect('no', done) + .get('/') + .expect('no', done) }) }) }) - describe('.secure', function(){ - describe('when X-Forwarded-Proto is present', function(){ - it('should return false when http', function(done){ - var app = express(); + describe('.secure', () => { + describe('when X-Forwarded-Proto is present', () => { + it('should return false when http', (done) => { + const app = express() - app.get('/', function(req, res){ - res.send(req.secure ? 'yes' : 'no'); - }); + app.get('/', (req, res) => { + res.send(req.secure ? 'yes' : 'no') + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('no', done) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('no', done) }) - it('should return true when "trust proxy" is enabled', function(done){ - var app = express(); + it('should return true when "trust proxy" is enabled', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.get('/', function(req, res){ - res.send(req.secure ? 'yes' : 'no'); - }); + app.get('/', (req, res) => { + res.send(req.secure ? 'yes' : 'no') + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('yes', done) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('yes', done) }) - it('should return false when initial proxy is http', function(done){ - var app = express(); + it('should return false when initial proxy is http', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.get('/', function(req, res){ - res.send(req.secure ? 'yes' : 'no'); - }); + app.get('/', (req, res) => { + res.send(req.secure ? 'yes' : 'no') + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'http, https') - .expect('no', done) + .get('/') + .set('X-Forwarded-Proto', 'http, https') + .expect('no', done) }) - it('should return true when initial proxy is https', function(done){ - var app = express(); + it('should return true when initial proxy is https', (done) => { + const app = express() - app.enable('trust proxy'); + app.enable('trust proxy') - app.get('/', function(req, res){ - res.send(req.secure ? 'yes' : 'no'); - }); + app.get('/', (req, res) => { + res.send(req.secure ? 'yes' : 'no') + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https, http') - .expect('yes', done) + .get('/') + .set('X-Forwarded-Proto', 'https, http') + .expect('yes', done) }) - describe('when "trust proxy" trusting hop count', function () { - it('should respect X-Forwarded-Proto', function (done) { - var app = express(); + describe('when "trust proxy" trusting hop count', () => { + it('should respect X-Forwarded-Proto', (done) => { + const app = express() - app.set('trust proxy', 1); + app.set('trust proxy', 1) - app.get('/', function (req, res) { - res.send(req.secure ? 'yes' : 'no'); - }); + app.get('/', (req, res) => { + res.send(req.secure ? 'yes' : 'no') + }) request(app) - .get('/') - .set('X-Forwarded-Proto', 'https') - .expect('yes', done) + .get('/') + .set('X-Forwarded-Proto', 'https') + .expect('yes', done) }) }) }) diff --git a/test/req.signedCookies.js b/test/req.signedCookies.js index db561951665..529dd324901 100644 --- a/test/req.signedCookies.js +++ b/test/req.signedCookies.js @@ -1,37 +1,36 @@ 'use strict' -var express = require('../') - , request = require('supertest') - , cookieParser = require('cookie-parser') +const express = require('../') +const request = require('supertest') +const cookieParser = require('cookie-parser') -describe('req', function(){ - describe('.signedCookies', function(){ - it('should return a signed JSON cookie', function(done){ - var app = express(); +describe('req', () => { + describe('.signedCookies', () => { + it('should return a signed JSON cookie', (done) => { + const app = express() - app.use(cookieParser('secret')); + app.use(cookieParser('secret')) - app.use(function(req, res){ + app.use((req, res) => { if (req.path === '/set') { - res.cookie('obj', { foo: 'bar' }, { signed: true }); - res.end(); + res.cookie('obj', { foo: 'bar' }, { signed: true }) + res.end() } else { - res.send(req.signedCookies); + res.send(req.signedCookies) } - }); + }) request(app) - .get('/set') - .end(function(err, res){ - if (err) return done(err); - var cookie = res.header['set-cookie']; + .get('/set') + .end((err, res) => { + if (err) return done(err) + const cookie = res.header['set-cookie'] - request(app) - .get('/') - .set('Cookie', cookie) - .expect(200, { obj: { foo: 'bar' } }, done) - }); + request(app) + .get('/') + .set('Cookie', cookie) + .expect(200, { obj: { foo: 'bar' } }, done) + }) }) }) }) - diff --git a/test/req.stale.js b/test/req.stale.js index cda77fa403e..7217121ed4c 100644 --- a/test/req.stale.js +++ b/test/req.stale.js @@ -1,50 +1,50 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.stale', function(){ - it('should return false when the resource is not modified', function(done){ - var app = express(); - var etag = '"12345"'; +describe('req', () => { + describe('.stale', () => { + it('should return false when the resource is not modified', (done) => { + const app = express() + const etag = '"12345"' - app.use(function(req, res){ - res.set('ETag', etag); - res.send(req.stale); - }); + app.use((req, res) => { + res.set('ETag', etag) + res.send(req.stale) + }) request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); + .get('/') + .set('If-None-Match', etag) + .expect(304, done) }) - it('should return true when the resource is modified', function(done){ - var app = express(); + it('should return true when the resource is modified', (done) => { + const app = express() - app.use(function(req, res){ - res.set('ETag', '"123"'); - res.send(req.stale); - }); + app.use((req, res) => { + res.set('ETag', '"123"') + res.send(req.stale) + }) request(app) - .get('/') - .set('If-None-Match', '"12345"') - .expect(200, 'true', done); + .get('/') + .set('If-None-Match', '"12345"') + .expect(200, 'true', done) }) - it('should return true without response headers', function(done){ - var app = express(); + it('should return true without response headers', (done) => { + const app = express() app.disable('x-powered-by') - app.use(function(req, res){ - res.send(req.stale); - }); + app.use((req, res) => { + res.send(req.stale) + }) request(app) - .get('/') - .expect(200, 'true', done); + .get('/') + .expect(200, 'true', done) }) }) }) diff --git a/test/req.subdomains.js b/test/req.subdomains.js index e5600f2eb56..01230b4e831 100644 --- a/test/req.subdomains.js +++ b/test/req.subdomains.js @@ -1,171 +1,171 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.subdomains', function(){ - describe('when present', function(){ - it('should return an array', function(done){ - var app = express(); +describe('req', () => { + describe('.subdomains', () => { + describe('when present', () => { + it('should return an array', (done) => { + const app = express() - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', 'tobi.ferrets.example.com') - .expect(200, ['ferrets', 'tobi'], done); + .get('/') + .set('Host', 'tobi.ferrets.example.com') + .expect(200, ['ferrets', 'tobi'], done) }) - it('should work with IPv4 address', function(done){ - var app = express(); + it('should work with IPv4 address', (done) => { + const app = express() - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', '127.0.0.1') - .expect(200, [], done); + .get('/') + .set('Host', '127.0.0.1') + .expect(200, [], done) }) - it('should work with IPv6 address', function(done){ - var app = express(); + it('should work with IPv6 address', (done) => { + const app = express() - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', '[::1]') - .expect(200, [], done); + .get('/') + .set('Host', '[::1]') + .expect(200, [], done) }) }) - describe('otherwise', function(){ - it('should return an empty array', function(done){ - var app = express(); + describe('otherwise', () => { + it('should return an empty array', (done) => { + const app = express() - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', 'example.com') - .expect(200, [], done); + .get('/') + .set('Host', 'example.com') + .expect(200, [], done) }) }) - describe('with no host', function(){ - it('should return an empty array', function(done){ - var app = express(); + describe('with no host', () => { + it('should return an empty array', (done) => { + const app = express() - app.use(function(req, res){ - req.headers.host = null; - res.send(req.subdomains); - }); + app.use((req, res) => { + req.headers.host = null + res.send(req.subdomains) + }) request(app) - .get('/') - .expect(200, [], done); + .get('/') + .expect(200, [], done) }) }) - describe('with trusted X-Forwarded-Host', function () { - it('should return an array', function (done) { - var app = express(); + describe('with trusted X-Forwarded-Host', () => { + it('should return an array', (done) => { + const app = express() - app.set('trust proxy', true); - app.use(function (req, res) { - res.send(req.subdomains); - }); + app.set('trust proxy', true) + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('X-Forwarded-Host', 'tobi.ferrets.example.com') - .expect(200, ['ferrets', 'tobi'], done); + .get('/') + .set('X-Forwarded-Host', 'tobi.ferrets.example.com') + .expect(200, ['ferrets', 'tobi'], done) }) }) - describe('when subdomain offset is set', function(){ - describe('when subdomain offset is zero', function(){ - it('should return an array with the whole domain', function(done){ - var app = express(); - app.set('subdomain offset', 0); + describe('when subdomain offset is set', () => { + describe('when subdomain offset is zero', () => { + it('should return an array with the whole domain', (done) => { + const app = express() + app.set('subdomain offset', 0) - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', 'tobi.ferrets.sub.example.com') - .expect(200, ['com', 'example', 'sub', 'ferrets', 'tobi'], done); + .get('/') + .set('Host', 'tobi.ferrets.sub.example.com') + .expect(200, ['com', 'example', 'sub', 'ferrets', 'tobi'], done) }) - it('should return an array with the whole IPv4', function (done) { - var app = express(); - app.set('subdomain offset', 0); + it('should return an array with the whole IPv4', (done) => { + const app = express() + app.set('subdomain offset', 0) - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', '127.0.0.1') - .expect(200, ['127.0.0.1'], done); + .get('/') + .set('Host', '127.0.0.1') + .expect(200, ['127.0.0.1'], done) }) - it('should return an array with the whole IPv6', function (done) { - var app = express(); - app.set('subdomain offset', 0); + it('should return an array with the whole IPv6', (done) => { + const app = express() + app.set('subdomain offset', 0) - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', '[::1]') - .expect(200, ['[::1]'], done); + .get('/') + .set('Host', '[::1]') + .expect(200, ['[::1]'], done) }) }) - describe('when present', function(){ - it('should return an array', function(done){ - var app = express(); - app.set('subdomain offset', 3); + describe('when present', () => { + it('should return an array', (done) => { + const app = express() + app.set('subdomain offset', 3) - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', 'tobi.ferrets.sub.example.com') - .expect(200, ['ferrets', 'tobi'], done); + .get('/') + .set('Host', 'tobi.ferrets.sub.example.com') + .expect(200, ['ferrets', 'tobi'], done) }) }) - describe('otherwise', function(){ - it('should return an empty array', function(done){ - var app = express(); - app.set('subdomain offset', 3); + describe('otherwise', () => { + it('should return an empty array', (done) => { + const app = express() + app.set('subdomain offset', 3) - app.use(function(req, res){ - res.send(req.subdomains); - }); + app.use((req, res) => { + res.send(req.subdomains) + }) request(app) - .get('/') - .set('Host', 'sub.example.com') - .expect(200, [], done); + .get('/') + .set('Host', 'sub.example.com') + .expect(200, [], done) }) }) }) diff --git a/test/req.xhr.js b/test/req.xhr.js index 99cf7f1917d..629f134230d 100644 --- a/test/req.xhr.js +++ b/test/req.xhr.js @@ -1,39 +1,39 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('req', function(){ - describe('.xhr', function(){ +describe('req', () => { + describe('.xhr', () => { before(function () { this.app = express() - this.app.get('/', function (req, res) { + this.app.get('/', (req, res) => { res.send(req.xhr) }) }) - it('should return true when X-Requested-With is xmlhttprequest', function(done){ + it('should return true when X-Requested-With is xmlhttprequest', function (done) { request(this.app) .get('/') .set('X-Requested-With', 'xmlhttprequest') .expect(200, 'true', done) }) - it('should case-insensitive', function(done){ + it('should case-insensitive', function (done) { request(this.app) .get('/') .set('X-Requested-With', 'XMLHttpRequest') .expect(200, 'true', done) }) - it('should return false otherwise', function(done){ + it('should return false otherwise', function (done) { request(this.app) .get('/') .set('X-Requested-With', 'blahblah') .expect(200, 'false', done) }) - it('should return false when not present', function(done){ + it('should return false when not present', function (done) { request(this.app) .get('/') .expect(200, 'false', done) diff --git a/test/res.append.js b/test/res.append.js index 2dd17a3a1fb..154c72f6c17 100644 --- a/test/res.append.js +++ b/test/res.append.js @@ -1,20 +1,20 @@ 'use strict' -var assert = require('node:assert') -var express = require('..') -var request = require('supertest') +const assert = require('node:assert') +const express = require('../') +const request = require('supertest') -describe('res', function () { - describe('.append(field, val)', function () { - it('should append multiple headers', function (done) { - var app = express() +describe('res', () => { + describe('.append(field, val)', () => { + it('should append multiple headers', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { res.append('Set-Cookie', 'foo=bar') next() }) - app.use(function (req, res) { + app.use((req, res) => { res.append('Set-Cookie', 'fizz=buzz') res.end() }) @@ -26,10 +26,10 @@ describe('res', function () { .end(done) }) - it('should accept array of values', function (done) { - var app = express() + it('should accept array of values', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { res.append('Set-Cookie', ['foo=bar', 'fizz=buzz']) res.end() }) @@ -41,19 +41,19 @@ describe('res', function () { .end(done) }) - it('should get reset by res.set(field, val)', function (done) { - var app = express() + it('should get reset by res.set(field, val)', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { res.append('Set-Cookie', 'foo=bar') res.append('Set-Cookie', 'fizz=buzz') next() }) - app.use(function (req, res) { + app.use((req, res) => { res.set('Set-Cookie', 'pet=tobi') res.end() - }); + }) request(app) .get('/') @@ -62,15 +62,15 @@ describe('res', function () { .end(done) }) - it('should work with res.set(field, val) first', function (done) { - var app = express() + it('should work with res.set(field, val) first', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { res.set('Set-Cookie', 'foo=bar') next() }) - app.use(function(req, res){ + app.use((req, res) => { res.append('Set-Cookie', 'fizz=buzz') res.end() }) @@ -82,15 +82,15 @@ describe('res', function () { .end(done) }) - it('should work together with res.cookie', function (done) { - var app = express() + it('should work together with res.cookie', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { res.cookie('foo', 'bar') next() }) - app.use(function (req, res) { + app.use((req, res) => { res.append('Set-Cookie', 'fizz=buzz') res.end() }) @@ -106,10 +106,10 @@ describe('res', function () { function shouldHaveHeaderValues (key, values) { return function (res) { - var headers = res.headers[key.toLowerCase()] + const headers = res.headers[key.toLowerCase()] assert.ok(headers, 'should have header "' + key + '"') assert.strictEqual(headers.length, values.length, 'should have ' + values.length + ' occurrences of "' + key + '"') - for (var i = 0; i < values.length; i++) { + for (let i = 0; i < values.length; i++) { assert.strictEqual(headers[i], values[i]) } } diff --git a/test/res.attachment.js b/test/res.attachment.js index 8644bab5b2d..686a9874cac 100644 --- a/test/res.attachment.js +++ b/test/res.attachment.js @@ -1,79 +1,79 @@ 'use strict' -const { Buffer } = require('node:buffer'); +const { Buffer } = require('node:buffer') -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('res', function(){ - describe('.attachment()', function(){ - it('should Content-Disposition to attachment', function(done){ - var app = express(); +describe('res', () => { + describe('.attachment()', () => { + it('should Content-Disposition to attachment', (done) => { + const app = express() - app.use(function(req, res){ - res.attachment().send('foo'); - }); + app.use((req, res) => { + res.attachment().send('foo') + }) request(app) - .get('/') - .expect('Content-Disposition', 'attachment', done); + .get('/') + .expect('Content-Disposition', 'attachment', done) }) }) - describe('.attachment(filename)', function(){ - it('should add the filename param', function(done){ - var app = express(); + describe('.attachment(filename)', () => { + it('should add the filename param', (done) => { + const app = express() - app.use(function(req, res){ - res.attachment('/path/to/image.png'); - res.send('foo'); - }); + app.use((req, res) => { + res.attachment('/path/to/image.png') + res.send('foo') + }) request(app) - .get('/') - .expect('Content-Disposition', 'attachment; filename="image.png"', done); + .get('/') + .expect('Content-Disposition', 'attachment; filename="image.png"', done) }) - it('should set the Content-Type', function(done){ - var app = express(); + it('should set the Content-Type', (done) => { + const app = express() - app.use(function(req, res){ - res.attachment('/path/to/image.png'); + app.use((req, res) => { + res.attachment('/path/to/image.png') res.send(Buffer.alloc(4, '.')) - }); + }) request(app) - .get('/') - .expect('Content-Type', 'image/png', done); + .get('/') + .expect('Content-Type', 'image/png', done) }) }) - describe('.attachment(utf8filename)', function(){ - it('should add the filename and filename* params', function(done){ - var app = express(); + describe('.attachment(utf8filename)', () => { + it('should add the filename and filename* params', (done) => { + const app = express() - app.use(function(req, res){ - res.attachment('/locales/日本語.txt'); - res.send('japanese'); - }); + app.use((req, res) => { + res.attachment('/locales/日本語.txt') + res.send('japanese') + }) request(app) - .get('/') - .expect('Content-Disposition', 'attachment; filename="???.txt"; filename*=UTF-8\'\'%E6%97%A5%E6%9C%AC%E8%AA%9E.txt') - .expect(200, done); + .get('/') + .expect('Content-Disposition', 'attachment; filename="???.txt"; filename*=UTF-8\'\'%E6%97%A5%E6%9C%AC%E8%AA%9E.txt') + .expect(200, done) }) - it('should set the Content-Type', function(done){ - var app = express(); + it('should set the Content-Type', (done) => { + const app = express() - app.use(function(req, res){ - res.attachment('/locales/日本語.txt'); - res.send('japanese'); - }); + app.use((req, res) => { + res.attachment('/locales/日本語.txt') + res.send('japanese') + }) request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8', done); + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8', done) }) }) }) diff --git a/test/res.clearCookie.js b/test/res.clearCookie.js index 74a746eb7be..4af1a8e1ebc 100644 --- a/test/res.clearCookie.js +++ b/test/res.clearCookie.js @@ -1,62 +1,62 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('res', function(){ - describe('.clearCookie(name)', function(){ - it('should set a cookie passed expiry', function(done){ - var app = express(); +describe('res', () => { + describe('.clearCookie(name)', () => { + it('should set a cookie passed expiry', (done) => { + const app = express() - app.use(function(req, res){ - res.clearCookie('sid').end(); - }); + app.use((req, res) => { + res.clearCookie('sid').end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT') + .expect(200, done) }) }) - describe('.clearCookie(name, options)', function(){ - it('should set the given params', function(done){ - var app = express(); + describe('.clearCookie(name, options)', () => { + it('should set the given params', (done) => { + const app = express() - app.use(function(req, res){ - res.clearCookie('sid', { path: '/admin' }).end(); - }); + app.use((req, res) => { + res.clearCookie('sid', { path: '/admin' }).end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') + .expect(200, done) }) - it('should ignore maxAge', function(done){ - var app = express(); + it('should ignore maxAge', (done) => { + const app = express() - app.use(function(req, res){ - res.clearCookie('sid', { path: '/admin', maxAge: 1000 }).end(); - }); + app.use((req, res) => { + res.clearCookie('sid', { path: '/admin', maxAge: 1000 }).end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') + .expect(200, done) }) - it('should ignore user supplied expires param', function(done){ - var app = express(); + it('should ignore user supplied expires param', (done) => { + const app = express() - app.use(function(req, res){ - res.clearCookie('sid', { path: '/admin', expires: new Date() }).end(); - }); + app.use((req, res) => { + res.clearCookie('sid', { path: '/admin', expires: new Date() }).end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') + .expect(200, done) }) }) }) diff --git a/test/res.cookie.js b/test/res.cookie.js index 180d1be3452..9a0a40fae17 100644 --- a/test/res.cookie.js +++ b/test/res.cookie.js @@ -1,48 +1,48 @@ 'use strict' -var express = require('../') - , request = require('supertest') - , cookieParser = require('cookie-parser') +const express = require('../') +const request = require('supertest') +const cookieParser = require('cookie-parser') -describe('res', function(){ - describe('.cookie(name, object)', function(){ - it('should generate a JSON cookie', function(done){ - var app = express(); +describe('res', () => { + describe('.cookie(name, object)', () => { + it('should generate a JSON cookie', (done) => { + const app = express() - app.use(function(req, res){ - res.cookie('user', { name: 'tobi' }).end(); - }); + app.use((req, res) => { + res.cookie('user', { name: 'tobi' }).end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'user=j%3A%7B%22name%22%3A%22tobi%22%7D; Path=/') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'user=j%3A%7B%22name%22%3A%22tobi%22%7D; Path=/') + .expect(200, done) }) }) - describe('.cookie(name, string)', function(){ - it('should set a cookie', function(done){ - var app = express(); + describe('.cookie(name, string)', () => { + it('should set a cookie', (done) => { + const app = express() - app.use(function(req, res){ - res.cookie('name', 'tobi').end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi').end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'name=tobi; Path=/') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'name=tobi; Path=/') + .expect(200, done) }) - it('should allow multiple calls', function(done){ - var app = express(); + it('should allow multiple calls', (done) => { + const app = express() - app.use(function(req, res){ - res.cookie('name', 'tobi'); - res.cookie('age', 1); - res.cookie('gender', '?'); - res.end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi') + res.cookie('age', 1) + res.cookie('gender', '?') + res.end() + }) request(app) .get('/') @@ -51,26 +51,26 @@ describe('res', function(){ }) }) - describe('.cookie(name, string, options)', function(){ - it('should set params', function(done){ - var app = express(); + describe('.cookie(name, string, options)', () => { + it('should set params', (done) => { + const app = express() - app.use(function(req, res){ - res.cookie('name', 'tobi', { httpOnly: true, secure: true }); - res.end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi', { httpOnly: true, secure: true }) + res.end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'name=tobi; Path=/; HttpOnly; Secure') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'name=tobi; Path=/; HttpOnly; Secure') + .expect(200, done) }) - describe('expires', function () { - it('should throw on invalid date', function (done) { - var app = express() + describe('expires', () => { + it('should throw on invalid date', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { expires: new Date(NaN) }) res.end() }) @@ -81,14 +81,14 @@ describe('res', function(){ }) }) - describe('partitioned', function () { - it('should set partitioned', function (done) { - var app = express(); + describe('partitioned', () => { + it('should set partitioned', (done) => { + const app = express() - app.use(function (req, res) { - res.cookie('name', 'tobi', { partitioned: true }); - res.end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi', { partitioned: true }) + res.end() + }) request(app) .get('/') @@ -97,14 +97,14 @@ describe('res', function(){ }) }) - describe('maxAge', function(){ - it('should set relative expires', function(done){ - var app = express(); + describe('maxAge', () => { + it('should set relative expires', (done) => { + const app = express() - app.use(function(req, res){ - res.cookie('name', 'tobi', { maxAge: 1000 }); - res.end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi', { maxAge: 1000 }) + res.end() + }) request(app) .get('/') @@ -112,39 +112,39 @@ describe('res', function(){ .expect(200, done) }) - it('should set max-age', function(done){ - var app = express(); + it('should set max-age', (done) => { + const app = express() - app.use(function(req, res){ - res.cookie('name', 'tobi', { maxAge: 1000 }); - res.end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi', { maxAge: 1000 }) + res.end() + }) request(app) - .get('/') - .expect('Set-Cookie', /Max-Age=1/, done) + .get('/') + .expect('Set-Cookie', /Max-Age=1/, done) }) - it('should not mutate the options object', function(done){ - var app = express(); + it('should not mutate the options object', (done) => { + const app = express() - var options = { maxAge: 1000 }; - var optionsCopy = { ...options }; + const options = { maxAge: 1000 } + const optionsCopy = { ...options } - app.use(function(req, res){ + app.use((req, res) => { res.cookie('name', 'tobi', options) res.json(options) - }); + }) request(app) - .get('/') - .expect(200, optionsCopy, done) + .get('/') + .expect(200, optionsCopy, done) }) - it('should not throw on null', function (done) { - var app = express() + it('should not throw on null', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { maxAge: null }) res.end() }) @@ -156,10 +156,10 @@ describe('res', function(){ .end(done) }) - it('should not throw on undefined', function (done) { - var app = express() + it('should not throw on undefined', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { maxAge: undefined }) res.end() }) @@ -171,10 +171,10 @@ describe('res', function(){ .end(done) }) - it('should throw an error with invalid maxAge', function (done) { - var app = express() + it('should throw an error with invalid maxAge', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { maxAge: 'foobar' }) res.end() }) @@ -185,11 +185,11 @@ describe('res', function(){ }) }) - describe('priority', function () { - it('should set low priority', function (done) { - var app = express() + describe('priority', () => { + it('should set low priority', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { priority: 'low' }) res.end() }) @@ -200,10 +200,10 @@ describe('res', function(){ .expect(200, done) }) - it('should set medium priority', function (done) { - var app = express() + it('should set medium priority', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { priority: 'medium' }) res.end() }) @@ -214,10 +214,10 @@ describe('res', function(){ .expect(200, done) }) - it('should set high priority', function (done) { - var app = express() + it('should set high priority', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { priority: 'high' }) res.end() }) @@ -228,10 +228,10 @@ describe('res', function(){ .expect(200, done) }) - it('should throw with invalid priority', function (done) { - var app = express() + it('should throw with invalid priority', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.cookie('name', 'tobi', { priority: 'foobar' }) res.end() }) @@ -242,15 +242,15 @@ describe('res', function(){ }) }) - describe('signed', function(){ - it('should generate a signed JSON cookie', function(done){ - var app = express(); + describe('signed', () => { + it('should generate a signed JSON cookie', (done) => { + const app = express() - app.use(cookieParser('foo bar baz')); + app.use(cookieParser('foo bar baz')) - app.use(function(req, res){ - res.cookie('user', { name: 'tobi' }, { signed: true }).end(); - }); + app.use((req, res) => { + res.cookie('user', { name: 'tobi' }, { signed: true }).end() + }) request(app) .get('/') @@ -259,36 +259,36 @@ describe('res', function(){ }) }) - describe('signed without secret', function(){ - it('should throw an error', function(done){ - var app = express(); + describe('signed without secret', () => { + it('should throw an error', (done) => { + const app = express() - app.use(cookieParser()); + app.use(cookieParser()) - app.use(function(req, res){ - res.cookie('name', 'tobi', { signed: true }).end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi', { signed: true }).end() + }) request(app) - .get('/') - .expect(500, /secret\S+ required for signed cookies/, done); + .get('/') + .expect(500, /secret\S+ required for signed cookies/, done) }) }) - describe('.signedCookie(name, string)', function(){ - it('should set a signed cookie', function(done){ - var app = express(); + describe('.signedCookie(name, string)', () => { + it('should set a signed cookie', (done) => { + const app = express() - app.use(cookieParser('foo bar baz')); + app.use(cookieParser('foo bar baz')) - app.use(function(req, res){ - res.cookie('name', 'tobi', { signed: true }).end(); - }); + app.use((req, res) => { + res.cookie('name', 'tobi', { signed: true }).end() + }) request(app) - .get('/') - .expect('Set-Cookie', 'name=s%3Atobi.xJjV2iZ6EI7C8E5kzwbfA9PVLl1ZR07UTnuTgQQ4EnQ; Path=/') - .expect(200, done) + .get('/') + .expect('Set-Cookie', 'name=s%3Atobi.xJjV2iZ6EI7C8E5kzwbfA9PVLl1ZR07UTnuTgQQ4EnQ; Path=/') + .expect(200, done) }) }) }) diff --git a/test/res.download.js b/test/res.download.js index e9966007eba..f664529f568 100644 --- a/test/res.download.js +++ b/test/res.download.js @@ -1,37 +1,37 @@ 'use strict' -var after = require('after'); -var assert = require('node:assert') -var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage -const { Buffer } = require('node:buffer'); +const after = require('after') +const assert = require('node:assert') +const { AsyncLocalStorage } = require('node:async_hooks') +const { Buffer } = require('node:buffer') -var express = require('..'); -var path = require('node:path') -var request = require('supertest'); -var utils = require('./support/utils') +const express = require('../') +const path = require('node:path') +const request = require('supertest') +const utils = require('./support/utils') -var FIXTURES_PATH = path.join(__dirname, 'fixtures') +const FIXTURES_PATH = path.join(__dirname, 'fixtures') -describe('res', function(){ - describe('.download(path)', function(){ - it('should transfer as an attachment', function(done){ - var app = express(); +describe('res', () => { + describe('.download(path)', () => { + it('should transfer as an attachment', (done) => { + const app = express() - app.use(function(req, res){ - res.download('test/fixtures/user.html'); - }); + app.use((req, res) => { + res.download('test/fixtures/user.html') + }) request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="user.html"') - .expect(200, '

        {{user.name}}

        ', done) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="user.html"') + .expect(200, '

        {{user.name}}

        ', done) }) - it('should accept range requests', function (done) { - var app = express() + it('should accept range requests', (done) => { + const app = express() - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.download('test/fixtures/user.html') }) @@ -41,10 +41,10 @@ describe('res', function(){ .expect(200, '

        {{user.name}}

        ', done) }) - it('should respond with requested byte range', function (done) { - var app = express() + it('should respond with requested byte range', (done) => { + const app = express() - app.get('/', function (req, res) { + app.get('/', (req, res) => { res.download('test/fixtures/user.html') }) @@ -56,54 +56,54 @@ describe('res', function(){ }) }) - describe('.download(path, filename)', function(){ - it('should provide an alternate filename', function(done){ - var app = express(); + describe('.download(path, filename)', () => { + it('should provide an alternate filename', (done) => { + const app = express() - app.use(function(req, res){ - res.download('test/fixtures/user.html', 'document'); - }); + app.use((req, res) => { + res.download('test/fixtures/user.html', 'document') + }) request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="document"') - .expect(200, done) + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="document"') + .expect(200, done) }) }) - describe('.download(path, fn)', function(){ - it('should invoke the callback', function(done){ - var app = express(); - var cb = after(2, done); + describe('.download(path, fn)', () => { + it('should invoke the callback', (done) => { + const app = express() + const cb = after(2, done) - app.use(function(req, res){ - res.download('test/fixtures/user.html', cb); - }); + app.use((req, res) => { + res.download('test/fixtures/user.html', cb) + }) request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="user.html"') - .expect(200, cb); + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="user.html"') + .expect(200, cb) }) - describe('async local storage', function () { - it('should persist store', function (done) { - var app = express() - var cb = after(2, done) - var store = { foo: 'bar' } + describe('async local storage', () => { + it('should persist store', (done) => { + const app = express() + const cb = after(2, done) + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) - app.use(function (req, res) { - res.download('test/fixtures/name.txt', function (err) { + app.use((req, res) => { + res.download('test/fixtures/name.txt', (err) => { if (err) return cb(err) - var local = req.asyncLocalStorage.getStore() + const local = req.asyncLocalStorage.getStore() assert.strictEqual(local.foo, 'bar') cb() @@ -117,18 +117,18 @@ describe('res', function(){ .expect(200, 'tobi', cb) }) - it('should persist store on error', function (done) { - var app = express() - var store = { foo: 'bar' } + it('should persist store on error', (done) => { + const app = express() + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) - app.use(function (req, res) { - res.download('test/fixtures/does-not-exist', function (err) { - var local = req.asyncLocalStorage.getStore() + app.use((req, res) => { + res.download('test/fixtures/does-not-exist', (err) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -148,11 +148,11 @@ describe('res', function(){ }) }) - describe('.download(path, options)', function () { - it('should allow options to res.sendFile()', function (done) { - var app = express() + describe('.download(path, options)', () => { + it('should allow options to res.sendFile()', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/.name', { dotfiles: 'allow', maxAge: '4h' @@ -168,11 +168,11 @@ describe('res', function(){ .end(done) }) - describe('with "headers" option', function () { - it('should set headers on response', function (done) { - var app = express() + describe('with "headers" option', () => { + it('should set headers on response', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', { headers: { 'X-Foo': 'Bar', @@ -189,10 +189,10 @@ describe('res', function(){ .end(done) }) - it('should use last header when duplicated', function (done) { - var app = express() + it('should use last header when duplicated', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', { headers: { 'X-Foo': 'Bar', @@ -208,10 +208,10 @@ describe('res', function(){ .end(done) }) - it('should override Content-Type', function (done) { - var app = express() + it('should override Content-Type', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', { headers: { 'Content-Type': 'text/x-custom' @@ -226,10 +226,10 @@ describe('res', function(){ .end(done) }) - it('should not set headers on 404', function (done) { - var app = express() + it('should not set headers on 404', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/does-not-exist', { headers: { 'X-Foo': 'Bar' @@ -244,11 +244,11 @@ describe('res', function(){ .end(done) }) - describe('when headers contains Content-Disposition', function () { - it('should be ignored', function (done) { - var app = express() + describe('when headers contains Content-Disposition', () => { + it('should be ignored', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', { headers: { 'Content-Disposition': 'inline' @@ -263,10 +263,10 @@ describe('res', function(){ .end(done) }) - it('should be ignored case-insensitively', function (done) { - var app = express() + it('should be ignored case-insensitively', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', { headers: { 'content-disposition': 'inline' @@ -283,11 +283,11 @@ describe('res', function(){ }) }) - describe('with "root" option', function () { - it('should allow relative path', function (done) { - var app = express() + describe('with "root" option', () => { + it('should allow relative path', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('name.txt', { root: FIXTURES_PATH }) @@ -301,10 +301,10 @@ describe('res', function(){ .end(done) }) - it('should allow up within root', function (done) { - var app = express() + it('should allow up within root', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('fake/../name.txt', { root: FIXTURES_PATH }) @@ -318,11 +318,11 @@ describe('res', function(){ .end(done) }) - it('should reject up outside root', function (done) { - var app = express() + it('should reject up outside root', (done) => { + const app = express() - app.use(function (req, res) { - var p = '..' + path.sep + + app.use((req, res) => { + const p = '..' + path.sep + path.relative(path.dirname(FIXTURES_PATH), path.join(FIXTURES_PATH, 'name.txt')) res.download(p, { @@ -337,10 +337,10 @@ describe('res', function(){ .end(done) }) - it('should reject reading outside root', function (done) { - var app = express() + it('should reject reading outside root', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('../name.txt', { root: FIXTURES_PATH }) @@ -355,45 +355,45 @@ describe('res', function(){ }) }) - describe('.download(path, filename, fn)', function(){ - it('should invoke the callback', function(done){ - var app = express(); - var cb = after(2, done); + describe('.download(path, filename, fn)', () => { + it('should invoke the callback', (done) => { + const app = express() + const cb = after(2, done) - app.use(function(req, res){ + app.use((req, res) => { res.download('test/fixtures/user.html', 'document', cb) - }); + }) request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="document"') - .expect(200, cb); + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="document"') + .expect(200, cb) }) }) - describe('.download(path, filename, options, fn)', function () { - it('should invoke the callback', function (done) { - var app = express() - var cb = after(2, done) - var options = {} + describe('.download(path, filename, options, fn)', () => { + it('should invoke the callback', (done) => { + const app = express() + const cb = after(2, done) + const options = {} - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', 'document', options, cb) }) request(app) - .get('/') - .expect(200) - .expect('Content-Type', 'text/html; charset=utf-8') - .expect('Content-Disposition', 'attachment; filename="document"') - .end(cb) + .get('/') + .expect(200) + .expect('Content-Type', 'text/html; charset=utf-8') + .expect('Content-Disposition', 'attachment; filename="document"') + .end(cb) }) - it('should allow options to res.sendFile()', function (done) { - var app = express() + it('should allow options to res.sendFile()', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/.name', 'document', { dotfiles: 'allow', maxAge: '4h' @@ -409,11 +409,11 @@ describe('res', function(){ .end(done) }) - describe('when options.headers contains Content-Disposition', function () { - it('should be ignored', function (done) { - var app = express() + describe('when options.headers contains Content-Disposition', () => { + it('should be ignored', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', 'document', { headers: { 'Content-Type': 'text/x-custom', @@ -423,17 +423,17 @@ describe('res', function(){ }) request(app) - .get('/') - .expect(200) - .expect('Content-Type', 'text/x-custom') - .expect('Content-Disposition', 'attachment; filename="document"') - .end(done) + .get('/') + .expect(200) + .expect('Content-Type', 'text/x-custom') + .expect('Content-Disposition', 'attachment; filename="document"') + .end(done) }) - it('should be ignored case-insensitively', function (done) { - var app = express() + it('should be ignored case-insensitively', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.download('test/fixtures/user.html', 'document', { headers: { 'content-type': 'text/x-custom', @@ -443,40 +443,40 @@ describe('res', function(){ }) request(app) - .get('/') - .expect(200) - .expect('Content-Type', 'text/x-custom') - .expect('Content-Disposition', 'attachment; filename="document"') - .end(done) + .get('/') + .expect(200) + .expect('Content-Type', 'text/x-custom') + .expect('Content-Disposition', 'attachment; filename="document"') + .end(done) }) }) }) - describe('on failure', function(){ - it('should invoke the callback', function(done){ - var app = express(); + describe('on failure', () => { + it('should invoke the callback', (done) => { + const app = express() - app.use(function (req, res, next) { - res.download('test/fixtures/foobar.html', function(err){ - if (!err) return next(new Error('expected error')); - res.send('got ' + err.status + ' ' + err.code); - }); - }); + app.use((req, res, next) => { + res.download('test/fixtures/foobar.html', (err) => { + if (!err) return next(new Error('expected error')) + res.send('got ' + err.status + ' ' + err.code) + }) + }) request(app) - .get('/') - .expect(200, 'got 404 ENOENT', done); + .get('/') + .expect(200, 'got 404 ENOENT', done) }) - it('should remove Content-Disposition', function(done){ - var app = express() + it('should remove Content-Disposition', (done) => { + const app = express() - app.use(function (req, res, next) { - res.download('test/fixtures/foobar.html', function(err){ - if (!err) return next(new Error('expected error')); - res.end('failed'); - }); - }); + app.use((req, res, next) => { + res.download('test/fixtures/foobar.html', (err) => { + if (!err) return next(new Error('expected error')) + res.end('failed') + }) + }) request(app) .get('/') diff --git a/test/res.format.js b/test/res.format.js index 0d770d57651..e46e48865b9 100644 --- a/test/res.format.js +++ b/test/res.format.js @@ -1,57 +1,57 @@ 'use strict' -var after = require('after') -var express = require('../') - , request = require('supertest') - , assert = require('node:assert'); +const after = require('after') +const express = require('../') +const request = require('supertest') +const assert = require('node:assert') -var app1 = express(); +const app1 = express() -app1.use(function(req, res, next){ +app1.use((req, res, next) => { res.format({ - 'text/plain': function(){ - res.send('hey'); + 'text/plain': function () { + res.send('hey') }, - 'text/html': function(){ - res.send('

        hey

        '); + 'text/html': function () { + res.send('

        hey

        ') }, - 'application/json': function(a, b, c){ + 'application/json': function (a, b, c) { assert(req === a) assert(res === b) assert(next === c) - res.send({ message: 'hey' }); + res.send({ message: 'hey' }) } - }); -}); + }) +}) -app1.use(function(err, req, res, next){ - if (!err.types) throw err; +app1.use((err, req, res, next) => { + if (!err.types) throw err res.status(err.status) res.send('Supports: ' + err.types.join(', ')) }) -var app2 = express(); +const app2 = express() -app2.use(function(req, res, next){ +app2.use((req, res, next) => { res.format({ - text: function(){ res.send('hey') }, - html: function(){ res.send('

        hey

        ') }, - json: function(){ res.send({ message: 'hey' }) } - }); -}); + text: function () { res.send('hey') }, + html: function () { res.send('

        hey

        ') }, + json: function () { res.send({ message: 'hey' }) } + }) +}) -app2.use(function(err, req, res, next){ +app2.use((err, req, res, next) => { res.status(err.status) res.send('Supports: ' + err.types.join(', ')) }) -var app3 = express(); +const app3 = express() -app3.use(function(req, res, next){ +app3.use((req, res, next) => { res.format({ - text: function(){ res.send('hey') }, + text: function () { res.send('hey') }, default: function (a, b, c) { assert(req === a) assert(res === b) @@ -59,79 +59,79 @@ app3.use(function(req, res, next){ res.send('default') } }) -}); +}) -var app4 = express(); +const app4 = express() -app4.get('/', function (req, res) { +app4.get('/', (req, res) => { res.format({ - text: function(){ res.send('hey') }, - html: function(){ res.send('

        hey

        ') }, - json: function(){ res.send({ message: 'hey' }) } - }); -}); + text: function () { res.send('hey') }, + html: function () { res.send('

        hey

        ') }, + json: function () { res.send({ message: 'hey' }) } + }) +}) -app4.use(function(err, req, res, next){ +app4.use((err, req, res, next) => { res.status(err.status) res.send('Supports: ' + err.types.join(', ')) }) -var app5 = express(); +const app5 = express() -app5.use(function (req, res, next) { +app5.use((req, res, next) => { res.format({ default: function () { res.send('hey') } - }); -}); + }) +}) -describe('res', function(){ - describe('.format(obj)', function(){ - describe('with canonicalized mime types', function(){ - test(app1); +describe('res', () => { + describe('.format(obj)', () => { + describe('with canonicalized mime types', () => { + test(app1) }) - describe('with extnames', function(){ - test(app2); + describe('with extnames', () => { + test(app2) }) - describe('with parameters', function(){ - var app = express(); + describe('with parameters', () => { + const app = express() - app.use(function(req, res, next){ + app.use((req, res, next) => { res.format({ - 'text/plain; charset=utf-8': function(){ res.send('hey') }, - 'text/html; foo=bar; bar=baz': function(){ res.send('

        hey

        ') }, - 'application/json; q=0.5': function(){ res.send({ message: 'hey' }) } - }); - }); + 'text/plain; charset=utf-8': function () { res.send('hey') }, + 'text/html; foo=bar; bar=baz': function () { res.send('

        hey

        ') }, + 'application/json; q=0.5': function () { res.send({ message: 'hey' }) } + }) + }) - app.use(function(err, req, res, next){ + app.use((err, req, res, next) => { res.status(err.status) res.send('Supports: ' + err.types.join(', ')) - }); + }) - test(app); + test(app) }) - describe('given .default', function(){ - it('should be invoked instead of auto-responding', function(done){ + describe('given .default', () => { + it('should be invoked instead of auto-responding', (done) => { request(app3) - .get('/') - .set('Accept', 'text/html') - .expect('default', done); + .get('/') + .set('Accept', 'text/html') + .expect('default', done) }) - it('should work when only .default is provided', function (done) { + it('should work when only .default is provided', (done) => { request(app5) - .get('/') - .set('Accept', '*/*') - .expect('hey', done); + .get('/') + .set('Accept', '*/*') + .expect('hey', done) }) - it('should be able to invoke other formatter', function (done) { - var app = express() + it('should be able to invoke other formatter', (done) => { + const app = express() - app.use(function (req, res, next) { + app.use((req, res, next) => { res.format({ json: function () { res.send('json') }, default: function () { @@ -151,23 +151,23 @@ describe('res', function(){ }) }) - describe('in router', function(){ - test(app4); + describe('in router', () => { + test(app4) }) - describe('in router', function(){ - var app = express(); - var router = express.Router(); + describe('in router', () => { + const app = express() + const router = express.Router() - router.get('/', function (req, res) { + router.get('/', (req, res) => { res.format({ - text: function(){ res.send('hey') }, - html: function(){ res.send('

        hey

        ') }, - json: function(){ res.send({ message: 'hey' }) } - }); - }); + text: function () { res.send('hey') }, + html: function () { res.send('

        hey

        ') }, + json: function () { res.send({ message: 'hey' }) } + }) + }) - router.use(function(err, req, res, next){ + router.use((err, req, res, next) => { res.status(err.status) res.send('Supports: ' + err.types.join(', ')) }) @@ -179,70 +179,70 @@ describe('res', function(){ }) }) -function test(app) { - it('should utilize qvalues in negotiation', function(done){ +function test (app) { + it('should utilize qvalues in negotiation', (done) => { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, application/json, */*; q=.1') - .expect({"message":"hey"}, done); + .get('/') + .set('Accept', 'text/html; q=.5, application/json, */*; q=.1') + .expect({ message: 'hey' }, done) }) - it('should allow wildcard type/subtypes', function(done){ + it('should allow wildcard type/subtypes', (done) => { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, application/*, */*; q=.1') - .expect({"message":"hey"}, done); + .get('/') + .set('Accept', 'text/html; q=.5, application/*, */*; q=.1') + .expect({ message: 'hey' }, done) }) - it('should default the Content-Type', function(done){ + it('should default the Content-Type', (done) => { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, text/plain') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect('hey', done); + .get('/') + .set('Accept', 'text/html; q=.5, text/plain') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect('hey', done) }) - it('should set the correct charset for the Content-Type', function (done) { - var cb = after(3, done) + it('should set the correct charset for the Content-Type', (done) => { + const cb = after(3, done) request(app) - .get('/') - .set('Accept', 'text/html') - .expect('Content-Type', 'text/html; charset=utf-8', cb) + .get('/') + .set('Accept', 'text/html') + .expect('Content-Type', 'text/html; charset=utf-8', cb) request(app) - .get('/') - .set('Accept', 'text/plain') - .expect('Content-Type', 'text/plain; charset=utf-8', cb) + .get('/') + .set('Accept', 'text/plain') + .expect('Content-Type', 'text/plain; charset=utf-8', cb) request(app) - .get('/') - .set('Accept', 'application/json') - .expect('Content-Type', 'application/json; charset=utf-8', cb) + .get('/') + .set('Accept', 'application/json') + .expect('Content-Type', 'application/json; charset=utf-8', cb) }) - it('should Vary: Accept', function(done){ + it('should Vary: Accept', (done) => { request(app) - .get('/') - .set('Accept', 'text/html; q=.5, text/plain') - .expect('Vary', 'Accept', done); + .get('/') + .set('Accept', 'text/html; q=.5, text/plain') + .expect('Vary', 'Accept', done) }) - describe('when Accept is not present', function(){ - it('should invoke the first callback', function(done){ + describe('when Accept is not present', () => { + it('should invoke the first callback', (done) => { request(app) - .get('/') - .expect('hey', done); + .get('/') + .expect('hey', done) }) }) - describe('when no match is made', function(){ - it('should respond with 406 not acceptable', function(done){ + describe('when no match is made', () => { + it('should respond with 406 not acceptable', (done) => { request(app) - .get('/') - .set('Accept', 'foo/bar') - .expect('Supports: text/plain, text/html, application/json') - .expect(406, done) + .get('/') + .set('Accept', 'foo/bar') + .expect('Supports: text/plain, text/html, application/json') + .expect(406, done) }) }) } diff --git a/test/res.get.js b/test/res.get.js index a5f12e2e539..9c4fba98222 100644 --- a/test/res.get.js +++ b/test/res.get.js @@ -1,21 +1,21 @@ 'use strict' -var express = require('..'); -var request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('res', function(){ - describe('.get(field)', function(){ - it('should get the response header field', function (done) { - var app = express(); +describe('res', () => { + describe('.get(field)', () => { + it('should get the response header field', (done) => { + const app = express() - app.use(function (req, res) { - res.setHeader('Content-Type', 'text/x-foo'); - res.send(res.get('Content-Type')); - }); + app.use((req, res) => { + res.setHeader('Content-Type', 'text/x-foo') + res.send(res.get('Content-Type')) + }) request(app) - .get('/') - .expect(200, 'text/x-foo', done); + .get('/') + .expect(200, 'text/x-foo', done) }) }) }) diff --git a/test/res.json.js b/test/res.json.js index ffd547e95b2..0a9f5517bae 100644 --- a/test/res.json.js +++ b/test/res.json.js @@ -1,135 +1,135 @@ 'use strict' -var express = require('../') - , request = require('supertest') - , assert = require('node:assert'); +const express = require('../') +const request = require('supertest') +const assert = require('node:assert') -describe('res', function(){ - describe('.json(object)', function(){ - it('should not support jsonp callbacks', function(done){ - var app = express(); +describe('res', () => { + describe('.json(object)', () => { + it('should not support jsonp callbacks', (done) => { + const app = express() - app.use(function(req, res){ - res.json({ foo: 'bar' }); - }); + app.use((req, res) => { + res.json({ foo: 'bar' }) + }) request(app) - .get('/?callback=foo') - .expect('{"foo":"bar"}', done); + .get('/?callback=foo') + .expect('{"foo":"bar"}', done) }) - it('should not override previous Content-Types', function(done){ - var app = express(); + it('should not override previous Content-Types', (done) => { + const app = express() - app.get('/', function(req, res){ - res.type('application/vnd.example+json'); - res.json({ hello: 'world' }); - }); + app.get('/', (req, res) => { + res.type('application/vnd.example+json') + res.json({ hello: 'world' }) + }) request(app) - .get('/') - .expect('Content-Type', 'application/vnd.example+json; charset=utf-8') - .expect(200, '{"hello":"world"}', done); + .get('/') + .expect('Content-Type', 'application/vnd.example+json; charset=utf-8') + .expect(200, '{"hello":"world"}', done) }) - describe('when given primitives', function(){ - it('should respond with json for null', function(done){ - var app = express(); + describe('when given primitives', () => { + it('should respond with json for null', (done) => { + const app = express() - app.use(function(req, res){ - res.json(null); - }); + app.use((req, res) => { + res.json(null) + }) request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, 'null', done) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, 'null', done) }) - it('should respond with json for Number', function(done){ - var app = express(); + it('should respond with json for Number', (done) => { + const app = express() - app.use(function(req, res){ - res.json(300); - }); + app.use((req, res) => { + res.json(300) + }) request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '300', done) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '300', done) }) - it('should respond with json for String', function(done){ - var app = express(); + it('should respond with json for String', (done) => { + const app = express() - app.use(function(req, res){ - res.json('str'); - }); + app.use((req, res) => { + res.json('str') + }) request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '"str"', done) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '"str"', done) }) }) - describe('when given an array', function(){ - it('should respond with json', function(done){ - var app = express(); + describe('when given an array', () => { + it('should respond with json', (done) => { + const app = express() - app.use(function(req, res){ - res.json(['foo', 'bar', 'baz']); - }); + app.use((req, res) => { + res.json(['foo', 'bar', 'baz']) + }) request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '["foo","bar","baz"]', done) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '["foo","bar","baz"]', done) }) }) - describe('when given an object', function(){ - it('should respond with json', function(done){ - var app = express(); + describe('when given an object', () => { + it('should respond with json', (done) => { + const app = express() - app.use(function(req, res){ - res.json({ name: 'tobi' }); - }); + app.use((req, res) => { + res.json({ name: 'tobi' }) + }) request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '{"name":"tobi"}', done) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '{"name":"tobi"}', done) }) }) - describe('"json escape" setting', function () { - it('should be undefined by default', function () { - var app = express() + describe('"json escape" setting', () => { + it('should be undefined by default', () => { + const app = express() assert.strictEqual(app.get('json escape'), undefined) }) - it('should unicode escape HTML-sniffing characters', function (done) { - var app = express() + it('should unicode escape HTML-sniffing characters', (done) => { + const app = express() app.enable('json escape') - app.use(function (req, res) { + app.use((req, res) => { res.json({ '&': ''); - }); + app.use((req, res) => { + res.redirect('http://example.com/?param=') + }) request(app) - .get('/') - .set('Host', 'http://example.com') - .set('Accept', 'text/plain, */*') - .expect('Content-Type', /plain/) - .expect('Location', 'http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E') - .expect(302, 'Found. Redirecting to http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E', done) + .get('/') + .set('Host', 'http://example.com') + .set('Accept', 'text/plain, */*') + .expect('Content-Type', /plain/) + .expect('Location', 'http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E') + .expect(302, 'Found. Redirecting to http://example.com/?param=%3Cscript%3Ealert(%22hax%22);%3C/script%3E', done) }) - it('should include the redirect type', function(done){ - var app = express(); + it('should include the redirect type', (done) => { + const app = express() - app.use(function(req, res){ - res.redirect(301, 'http://google.com'); - }); + app.use((req, res) => { + res.redirect(301, 'http://google.com') + }) request(app) - .get('/') - .set('Accept', 'text/plain, */*') - .expect('Content-Type', /plain/) - .expect('Location', 'http://google.com') - .expect(301, 'Moved Permanently. Redirecting to http://google.com', done); + .get('/') + .set('Accept', 'text/plain, */*') + .expect('Content-Type', /plain/) + .expect('Location', 'http://google.com') + .expect(301, 'Moved Permanently. Redirecting to http://google.com', done) }) }) - describe('when accepting neither text or html', function(){ - it('should respond with an empty body', function(done){ - var app = express(); + describe('when accepting neither text or html', () => { + it('should respond with an empty body', (done) => { + const app = express() - app.use(function(req, res){ - res.redirect('http://google.com'); - }); + app.use((req, res) => { + res.redirect('http://google.com') + }) request(app) .get('/') diff --git a/test/res.render.js b/test/res.render.js index 114b398e0b4..9fc7d1362e3 100644 --- a/test/res.render.js +++ b/test/res.render.js @@ -1,367 +1,367 @@ 'use strict' -var express = require('..'); -var path = require('node:path') -var request = require('supertest'); -var tmpl = require('./support/tmpl'); +const express = require('../') +const path = require('node:path') +const request = require('supertest') +const tmpl = require('./support/tmpl') -describe('res', function(){ - describe('.render(name)', function(){ - it('should support absolute paths', function(done){ - var app = createApp(); +describe('res', () => { + describe('.render(name)', () => { + it('should support absolute paths', (done) => { + const app = createApp() - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.use(function(req, res){ + app.use((req, res) => { res.render(path.join(__dirname, 'fixtures', 'user.tmpl')) - }); + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - it('should support absolute paths with "view engine"', function(done){ - var app = createApp(); + it('should support absolute paths with "view engine"', (done) => { + const app = createApp() - app.locals.user = { name: 'tobi' }; - app.set('view engine', 'tmpl'); + app.locals.user = { name: 'tobi' } + app.set('view engine', 'tmpl') - app.use(function(req, res){ + app.use((req, res) => { res.render(path.join(__dirname, 'fixtures', 'user')) - }); + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - it('should error without "view engine" set and file extension to a non-engine module', function (done) { - var app = createApp() + it('should error without "view engine" set and file extension to a non-engine module', (done) => { + const app = createApp() app.locals.user = { name: 'tobi' } - app.use(function (req, res) { + app.use((req, res) => { res.render(path.join(__dirname, 'fixtures', 'broken.send')) }) request(app) - .get('/') - .expect(500, /does not provide a view engine/, done) + .get('/') + .expect(500, /does not provide a view engine/, done) }) - it('should error without "view engine" set and no file extension', function (done) { - var app = createApp(); + it('should error without "view engine" set and no file extension', (done) => { + const app = createApp() - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.use(function(req, res){ + app.use((req, res) => { res.render(path.join(__dirname, 'fixtures', 'user')) - }); + }) request(app) - .get('/') - .expect(500, /No default engine was specified/, done); + .get('/') + .expect(500, /No default engine was specified/, done) }) - it('should expose app.locals', function(done){ - var app = createApp(); + it('should expose app.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.use(function(req, res){ - res.render('user.tmpl'); - }); + app.use((req, res) => { + res.render('user.tmpl') + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - it('should expose app.locals with `name` property', function(done){ - var app = createApp(); + it('should expose app.locals with `name` property', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.name = 'tobi'; + app.locals.name = 'tobi' - app.use(function(req, res){ - res.render('name.tmpl'); - }); + app.use((req, res) => { + res.render('name.tmpl') + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - it('should support index.', function(done){ - var app = createApp(); + it('should support index.', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.set('view engine', 'tmpl'); + app.set('view engine', 'tmpl') - app.use(function(req, res){ - res.render('blog/post'); - }); + app.use((req, res) => { + res.render('blog/post') + }) request(app) - .get('/') - .expect('

        blog post

        ', done); + .get('/') + .expect('

        blog post

        ', done) }) - describe('when an error occurs', function(){ - it('should next(err)', function(done){ - var app = createApp(); + describe('when an error occurs', () => { + it('should next(err)', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.use(function(req, res){ - res.render('user.tmpl'); - }); + app.use((req, res) => { + res.render('user.tmpl') + }) - app.use(function(err, req, res, next){ + app.use((err, req, res, next) => { res.status(500).send('got error: ' + err.name) - }); + }) request(app) - .get('/') - .expect(500, 'got error: RenderError', done) + .get('/') + .expect(500, 'got error: RenderError', done) }) }) - describe('when "view engine" is given', function(){ - it('should render the template', function(done){ - var app = createApp(); + describe('when "view engine" is given', () => { + it('should render the template', (done) => { + const app = createApp() - app.set('view engine', 'tmpl'); + app.set('view engine', 'tmpl') app.set('views', path.join(__dirname, 'fixtures')) - app.use(function(req, res){ - res.render('email'); - }); + app.use((req, res) => { + res.render('email') + }) request(app) - .get('/') - .expect('

        This is an email

        ', done); + .get('/') + .expect('

        This is an email

        ', done) }) }) - describe('when "views" is given', function(){ - it('should lookup the file in the path', function(done){ - var app = createApp(); + describe('when "views" is given', () => { + it('should lookup the file in the path', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures', 'default_layout')) - app.use(function(req, res){ - res.render('user.tmpl', { user: { name: 'tobi' } }); - }); + app.use((req, res) => { + res.render('user.tmpl', { user: { name: 'tobi' } }) + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - describe('when array of paths', function(){ - it('should lookup the file in the path', function(done){ - var app = createApp(); - var views = [ + describe('when array of paths', () => { + it('should lookup the file in the path', (done) => { + const app = createApp() + const views = [ path.join(__dirname, 'fixtures', 'local_layout'), path.join(__dirname, 'fixtures', 'default_layout') ] - app.set('views', views); + app.set('views', views) - app.use(function(req, res){ - res.render('user.tmpl', { user: { name: 'tobi' } }); - }); + app.use((req, res) => { + res.render('user.tmpl', { user: { name: 'tobi' } }) + }) request(app) - .get('/') - .expect('tobi', done); + .get('/') + .expect('tobi', done) }) - it('should lookup in later paths until found', function(done){ - var app = createApp(); - var views = [ + it('should lookup in later paths until found', (done) => { + const app = createApp() + const views = [ path.join(__dirname, 'fixtures', 'local_layout'), path.join(__dirname, 'fixtures', 'default_layout') ] - app.set('views', views); + app.set('views', views) - app.use(function(req, res){ - res.render('name.tmpl', { name: 'tobi' }); - }); + app.use((req, res) => { + res.render('name.tmpl', { name: 'tobi' }) + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) }) }) }) - describe('.render(name, option)', function(){ - it('should render the template', function(done){ - var app = createApp(); + describe('.render(name, option)', () => { + it('should render the template', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - var user = { name: 'tobi' }; + const user = { name: 'tobi' } - app.use(function(req, res){ - res.render('user.tmpl', { user: user }); - }); + app.use((req, res) => { + res.render('user.tmpl', { user }) + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - it('should expose app.locals', function(done){ - var app = createApp(); + it('should expose app.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.use(function(req, res){ - res.render('user.tmpl'); - }); + app.use((req, res) => { + res.render('user.tmpl') + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - it('should expose res.locals', function(done){ - var app = createApp(); + it('should expose res.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.use(function(req, res){ - res.locals.user = { name: 'tobi' }; - res.render('user.tmpl'); - }); + app.use((req, res) => { + res.locals.user = { name: 'tobi' } + res.render('user.tmpl') + }) request(app) - .get('/') - .expect('

        tobi

        ', done); + .get('/') + .expect('

        tobi

        ', done) }) - it('should give precedence to res.locals over app.locals', function(done){ - var app = createApp(); + it('should give precedence to res.locals over app.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.user = { name: 'tobi' }; + app.locals.user = { name: 'tobi' } - app.use(function(req, res){ - res.locals.user = { name: 'jane' }; - res.render('user.tmpl', {}); - }); + app.use((req, res) => { + res.locals.user = { name: 'jane' } + res.render('user.tmpl', {}) + }) request(app) - .get('/') - .expect('

        jane

        ', done); + .get('/') + .expect('

        jane

        ', done) }) - it('should give precedence to res.render() locals over res.locals', function(done){ - var app = createApp(); + it('should give precedence to res.render() locals over res.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - var jane = { name: 'jane' }; + const jane = { name: 'jane' } - app.use(function(req, res){ - res.locals.user = { name: 'tobi' }; - res.render('user.tmpl', { user: jane }); - }); + app.use((req, res) => { + res.locals.user = { name: 'tobi' } + res.render('user.tmpl', { user: jane }) + }) request(app) - .get('/') - .expect('

        jane

        ', done); + .get('/') + .expect('

        jane

        ', done) }) - it('should give precedence to res.render() locals over app.locals', function(done){ - var app = createApp(); + it('should give precedence to res.render() locals over app.locals', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.locals.user = { name: 'tobi' }; - var jane = { name: 'jane' }; + app.locals.user = { name: 'tobi' } + const jane = { name: 'jane' } - app.use(function(req, res){ - res.render('user.tmpl', { user: jane }); - }); + app.use((req, res) => { + res.render('user.tmpl', { user: jane }) + }) request(app) - .get('/') - .expect('

        jane

        ', done); + .get('/') + .expect('

        jane

        ', done) }) }) - describe('.render(name, options, fn)', function(){ - it('should pass the resulting string', function(done){ - var app = createApp(); + describe('.render(name, options, fn)', () => { + it('should pass the resulting string', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.use(function(req, res){ - var tobi = { name: 'tobi' }; - res.render('user.tmpl', { user: tobi }, function (err, html) { - html = html.replace('tobi', 'loki'); - res.end(html); - }); - }); + app.use((req, res) => { + const tobi = { name: 'tobi' } + res.render('user.tmpl', { user: tobi }, (err, html) => { + html = html.replace('tobi', 'loki') + res.end(html) + }) + }) request(app) - .get('/') - .expect('

        loki

        ', done); + .get('/') + .expect('

        loki

        ', done) }) }) - describe('.render(name, fn)', function(){ - it('should pass the resulting string', function(done){ - var app = createApp(); + describe('.render(name, fn)', () => { + it('should pass the resulting string', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.use(function(req, res){ - res.locals.user = { name: 'tobi' }; - res.render('user.tmpl', function (err, html) { - html = html.replace('tobi', 'loki'); - res.end(html); - }); - }); + app.use((req, res) => { + res.locals.user = { name: 'tobi' } + res.render('user.tmpl', (err, html) => { + html = html.replace('tobi', 'loki') + res.end(html) + }) + }) request(app) - .get('/') - .expect('

        loki

        ', done); + .get('/') + .expect('

        loki

        ', done) }) - describe('when an error occurs', function(){ - it('should pass it to the callback', function(done){ - var app = createApp(); + describe('when an error occurs', () => { + it('should pass it to the callback', (done) => { + const app = createApp() app.set('views', path.join(__dirname, 'fixtures')) - app.use(function(req, res){ - res.render('user.tmpl', function (err) { + app.use((req, res) => { + res.render('user.tmpl', (err) => { if (err) { res.status(500).send('got error: ' + err.name) } - }); - }); + }) + }) request(app) - .get('/') - .expect(500, 'got error: RenderError', done) + .get('/') + .expect(500, 'got error: RenderError', done) }) }) }) }) -function createApp() { - var app = express(); +function createApp () { + const app = express() - app.engine('.tmpl', tmpl); + app.engine('.tmpl', tmpl) - return app; + return app } diff --git a/test/res.send.js b/test/res.send.js index 8547b77648b..7cfec26d782 100644 --- a/test/res.send.js +++ b/test/res.send.js @@ -1,148 +1,148 @@ 'use strict' -var assert = require('node:assert') -const { Buffer } = require('node:buffer'); -var express = require('..'); -var methods = require('../lib/utils').methods; -var request = require('supertest'); -var utils = require('./support/utils'); - -var shouldSkipQuery = require('./support/utils').shouldSkipQuery - -describe('res', function(){ - describe('.send()', function(){ - it('should set body to ""', function(done){ - var app = express(); - - app.use(function(req, res){ - res.send(); - }); +const assert = require('node:assert') +const { Buffer } = require('node:buffer') +const express = require('../') +const { methods } = require('../lib/utils') +const request = require('supertest') +const utils = require('./support/utils') + +const { shouldSkipQuery } = require('./support/utils') + +describe('res', () => { + describe('.send()', () => { + it('should set body to ""', (done) => { + const app = express() + + app.use((req, res) => { + res.send() + }) request(app) - .get('/') - .expect(200, '', done); + .get('/') + .expect(200, '', done) }) }) - describe('.send(null)', function(){ - it('should set body to ""', function(done){ - var app = express(); + describe('.send(null)', () => { + it('should set body to ""', (done) => { + const app = express() - app.use(function(req, res){ - res.send(null); - }); + app.use((req, res) => { + res.send(null) + }) request(app) - .get('/') - .expect('Content-Length', '0') - .expect(200, '', done); + .get('/') + .expect('Content-Length', '0') + .expect(200, '', done) }) }) - describe('.send(undefined)', function(){ - it('should set body to ""', function(done){ - var app = express(); + describe('.send(undefined)', () => { + it('should set body to ""', (done) => { + const app = express() - app.use(function(req, res){ - res.send(undefined); - }); + app.use((req, res) => { + res.send(undefined) + }) request(app) - .get('/') - .expect(200, '', done); + .get('/') + .expect(200, '', done) }) }) - describe('.send(Number)', function(){ - it('should send as application/json', function(done){ - var app = express(); + describe('.send(Number)', () => { + it('should send as application/json', (done) => { + const app = express() - app.use(function(req, res){ - res.send(1000); - }); + app.use((req, res) => { + res.send(1000) + }) request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '1000', done) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '1000', done) }) }) - describe('.send(String)', function(){ - it('should send as html', function(done){ - var app = express(); + describe('.send(String)', () => { + it('should send as html', (done) => { + const app = express() - app.use(function(req, res){ - res.send('

        hey

        '); - }); + app.use((req, res) => { + res.send('

        hey

        ') + }) request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=utf-8') - .expect(200, '

        hey

        ', done); + .get('/') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect(200, '

        hey

        ', done) }) - it('should set ETag', function (done) { - var app = express(); + it('should set ETag', (done) => { + const app = express() - app.use(function (req, res) { - var str = Array(1000).join('-'); - res.send(str); - }); + app.use((req, res) => { + const str = Array(1000).join('-') + res.send(str) + }) request(app) - .get('/') - .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') - .expect(200, done); + .get('/') + .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') + .expect(200, done) }) - it('should not override Content-Type', function(done){ - var app = express(); + it('should not override Content-Type', (done) => { + const app = express() - app.use(function(req, res){ - res.set('Content-Type', 'text/plain').send('hey'); - }); + app.use((req, res) => { + res.set('Content-Type', 'text/plain').send('hey') + }) request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, 'hey', done); + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200, 'hey', done) }) - it('should override charset in Content-Type', function(done){ - var app = express(); + it('should override charset in Content-Type', (done) => { + const app = express() - app.use(function(req, res){ - res.set('Content-Type', 'text/plain; charset=iso-8859-1').send('hey'); - }); + app.use((req, res) => { + res.set('Content-Type', 'text/plain; charset=iso-8859-1').send('hey') + }) request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, 'hey', done); + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200, 'hey', done) }) - it('should keep charset in Content-Type for Buffers', function(done){ - var app = express(); + it('should keep charset in Content-Type for Buffers', (done) => { + const app = express() - app.use(function(req, res){ + app.use((req, res) => { res.set('Content-Type', 'text/plain; charset=iso-8859-1').send(Buffer.from('hi')) - }); + }) request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=iso-8859-1') - .expect(200, 'hi', done); + .get('/') + .expect('Content-Type', 'text/plain; charset=iso-8859-1') + .expect(200, 'hi', done) }) }) - describe('.send(Buffer)', function(){ - it('should send as octet-stream', function(done){ - var app = express(); + describe('.send(Buffer)', () => { + it('should send as octet-stream', (done) => { + const app = express() - app.use(function(req, res){ + app.use((req, res) => { res.send(Buffer.from('hello')) - }); + }) request(app) .get('/') @@ -152,81 +152,81 @@ describe('res', function(){ .end(done) }) - it('should set ETag', function (done) { - var app = express(); + it('should set ETag', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.send(Buffer.alloc(999, '-')) - }); + }) request(app) - .get('/') - .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') - .expect(200, done); + .get('/') + .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') + .expect(200, done) }) - it('should not override Content-Type', function(done){ - var app = express(); + it('should not override Content-Type', (done) => { + const app = express() - app.use(function(req, res){ + app.use((req, res) => { res.set('Content-Type', 'text/plain').send(Buffer.from('hey')) - }); + }) request(app) - .get('/') - .expect('Content-Type', 'text/plain; charset=utf-8') - .expect(200, 'hey', done); + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200, 'hey', done) }) - it('should accept Uint8Array', function(done){ - var app = express(); - app.use(function(req, res){ - const encodedHey = new TextEncoder().encode("hey"); - res.set("Content-Type", "text/plain").send(encodedHey); + it('should accept Uint8Array', (done) => { + const app = express() + app.use((req, res) => { + const encodedHey = new TextEncoder().encode('hey') + res.set('Content-Type', 'text/plain').send(encodedHey) }) request(app) - .get("/") - .expect("Content-Type", "text/plain; charset=utf-8") - .expect(200, "hey", done); + .get('/') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200, 'hey', done) }) - it('should not override ETag', function (done) { - var app = express() + it('should not override ETag', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.type('text/plain').set('ETag', '"foo"').send(Buffer.from('hey')) }) request(app) - .get('/') - .expect('ETag', '"foo"') - .expect(200, 'hey', done) + .get('/') + .expect('ETag', '"foo"') + .expect(200, 'hey', done) }) }) - describe('.send(Object)', function(){ - it('should send as application/json', function(done){ - var app = express(); + describe('.send(Object)', () => { + it('should send as application/json', (done) => { + const app = express() - app.use(function(req, res){ - res.send({ name: 'tobi' }); - }); + app.use((req, res) => { + res.send({ name: 'tobi' }) + }) request(app) - .get('/') - .expect('Content-Type', 'application/json; charset=utf-8') - .expect(200, '{"name":"tobi"}', done) + .get('/') + .expect('Content-Type', 'application/json; charset=utf-8') + .expect(200, '{"name":"tobi"}', done) }) }) - describe('when the request method is HEAD', function(){ - it('should ignore the body', function(done){ - var app = express(); + describe('when the request method is HEAD', () => { + it('should ignore the body', (done) => { + const app = express() - app.use(function(req, res){ - res.send('yay'); - }); + app.use((req, res) => { + res.send('yay') + }) request(app) .head('/') @@ -236,28 +236,28 @@ describe('res', function(){ }) }) - describe('when .statusCode is 204', function(){ - it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){ - var app = express(); + describe('when .statusCode is 204', () => { + it('should strip Content-* fields, Transfer-Encoding field, and body', (done) => { + const app = express() - app.use(function(req, res){ - res.status(204).set('Transfer-Encoding', 'chunked').send('foo'); - }); + app.use((req, res) => { + res.status(204).set('Transfer-Encoding', 'chunked').send('foo') + }) request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('Content-Type')) - .expect(utils.shouldNotHaveHeader('Content-Length')) - .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) - .expect(204, '', done); + .get('/') + .expect(utils.shouldNotHaveHeader('Content-Type')) + .expect(utils.shouldNotHaveHeader('Content-Length')) + .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) + .expect(204, '', done) }) }) - describe('when .statusCode is 205', function () { - it('should strip Transfer-Encoding field and body, set Content-Length', function (done) { - var app = express() + describe('when .statusCode is 205', () => { + it('should strip Transfer-Encoding field and body, set Content-Length', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(205).set('Transfer-Encoding', 'chunked').send('foo') }) @@ -269,300 +269,297 @@ describe('res', function(){ }) }) - describe('when .statusCode is 304', function(){ - it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){ - var app = express(); + describe('when .statusCode is 304', () => { + it('should strip Content-* fields, Transfer-Encoding field, and body', (done) => { + const app = express() - app.use(function(req, res){ - res.status(304).set('Transfer-Encoding', 'chunked').send('foo'); - }); + app.use((req, res) => { + res.status(304).set('Transfer-Encoding', 'chunked').send('foo') + }) request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('Content-Type')) - .expect(utils.shouldNotHaveHeader('Content-Length')) - .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) - .expect(304, '', done); + .get('/') + .expect(utils.shouldNotHaveHeader('Content-Type')) + .expect(utils.shouldNotHaveHeader('Content-Length')) + .expect(utils.shouldNotHaveHeader('Transfer-Encoding')) + .expect(304, '', done) }) }) - it('should always check regardless of length', function(done){ - var app = express(); - var etag = '"asdf"'; + it('should always check regardless of length', (done) => { + const app = express() + const etag = '"asdf"' - app.use(function(req, res, next){ - res.set('ETag', etag); - res.send('hey'); - }); + app.use((req, res, next) => { + res.set('ETag', etag) + res.send('hey') + }) request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); + .get('/') + .set('If-None-Match', etag) + .expect(304, done) }) - it('should respond with 304 Not Modified when fresh', function(done){ - var app = express(); - var etag = '"asdf"'; + it('should respond with 304 Not Modified when fresh', (done) => { + const app = express() + const etag = '"asdf"' - app.use(function(req, res){ - var str = Array(1000).join('-'); - res.set('ETag', etag); - res.send(str); - }); + app.use((req, res) => { + const str = Array(1000).join('-') + res.set('ETag', etag) + res.send(str) + }) request(app) - .get('/') - .set('If-None-Match', etag) - .expect(304, done); + .get('/') + .set('If-None-Match', etag) + .expect(304, done) }) - it('should not perform freshness check unless 2xx or 304', function(done){ - var app = express(); - var etag = '"asdf"'; + it('should not perform freshness check unless 2xx or 304', (done) => { + const app = express() + const etag = '"asdf"' - app.use(function(req, res, next){ - res.status(500); - res.set('ETag', etag); - res.send('hey'); - }); + app.use((req, res, next) => { + res.status(500) + res.set('ETag', etag) + res.send('hey') + }) request(app) - .get('/') - .set('If-None-Match', etag) - .expect('hey') - .expect(500, done); + .get('/') + .set('If-None-Match', etag) + .expect('hey') + .expect(500, done) }) - it('should not support jsonp callbacks', function(done){ - var app = express(); + it('should not support jsonp callbacks', (done) => { + const app = express() - app.use(function(req, res){ - res.send({ foo: 'bar' }); - }); + app.use((req, res) => { + res.send({ foo: 'bar' }) + }) request(app) - .get('/?callback=foo') - .expect('{"foo":"bar"}', done); + .get('/?callback=foo') + .expect('{"foo":"bar"}', done) }) - it('should be chainable', function (done) { - var app = express() + it('should be chainable', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { assert.equal(res.send('hey'), res) }) request(app) - .get('/') - .expect(200, 'hey', done) + .get('/') + .expect(200, 'hey', done) }) - describe('"etag" setting', function () { - describe('when enabled', function () { - it('should send ETag', function (done) { - var app = express(); + describe('"etag" setting', () => { + describe('when enabled', () => { + it('should send ETag', (done) => { + const app = express() - app.use(function (req, res) { - res.send('kajdslfkasdf'); - }); + app.use((req, res) => { + res.send('kajdslfkasdf') + }) - app.enable('etag'); + app.enable('etag') request(app) - .get('/') - .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') - .expect(200, done); - }); + .get('/') + .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') + .expect(200, done) + }) - methods.forEach(function (method) { - if (method === 'connect') return; + methods.forEach((method) => { + if (method === 'connect') return it('should send ETag in response to ' + method.toUpperCase() + ' request', function (done) { if (method === 'query' && shouldSkipQuery(process.versions.node)) { this.skip() } - var app = express(); + const app = express() - app[method]('/', function (req, res) { - res.send('kajdslfkasdf'); - }); + app[method]('/', (req, res) => { + res.send('kajdslfkasdf') + }) - request(app) - [method]('/') - .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') - .expect(200, done); + request(app)[method]('/') + .expect('ETag', 'W/"c-IgR/L5SF7CJQff4wxKGF/vfPuZ0"') + .expect(200, done) }) - }); + }) - it('should send ETag for empty string response', function (done) { - var app = express(); + it('should send ETag for empty string response', (done) => { + const app = express() - app.use(function (req, res) { - res.send(''); - }); + app.use((req, res) => { + res.send('') + }) - app.enable('etag'); + app.enable('etag') request(app) - .get('/') - .expect('ETag', 'W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') - .expect(200, done); + .get('/') + .expect('ETag', 'W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') + .expect(200, done) }) - it('should send ETag for long response', function (done) { - var app = express(); + it('should send ETag for long response', (done) => { + const app = express() - app.use(function (req, res) { - var str = Array(1000).join('-'); - res.send(str); - }); + app.use((req, res) => { + const str = Array(1000).join('-') + res.send(str) + }) - app.enable('etag'); + app.enable('etag') request(app) - .get('/') - .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') - .expect(200, done); - }); + .get('/') + .expect('ETag', 'W/"3e7-qPnkJ3CVdVhFJQvUBfF10TmVA7g"') + .expect(200, done) + }) - it('should not override ETag when manually set', function (done) { - var app = express(); + it('should not override ETag when manually set', (done) => { + const app = express() - app.use(function (req, res) { - res.set('etag', '"asdf"'); - res.send('hello!'); - }); + app.use((req, res) => { + res.set('etag', '"asdf"') + res.send('hello!') + }) - app.enable('etag'); + app.enable('etag') request(app) - .get('/') - .expect('ETag', '"asdf"') - .expect(200, done); - }); + .get('/') + .expect('ETag', '"asdf"') + .expect(200, done) + }) - it('should not send ETag for res.send()', function (done) { - var app = express(); + it('should not send ETag for res.send()', (done) => { + const app = express() - app.use(function (req, res) { - res.send(); - }); + app.use((req, res) => { + res.send() + }) - app.enable('etag'); + app.enable('etag') request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('ETag')) - .expect(200, done); + .get('/') + .expect(utils.shouldNotHaveHeader('ETag')) + .expect(200, done) }) - }); + }) - describe('when disabled', function () { - it('should send no ETag', function (done) { - var app = express(); + describe('when disabled', () => { + it('should send no ETag', (done) => { + const app = express() - app.use(function (req, res) { - var str = Array(1000).join('-'); - res.send(str); - }); + app.use((req, res) => { + const str = Array(1000).join('-') + res.send(str) + }) - app.disable('etag'); + app.disable('etag') request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('ETag')) - .expect(200, done); - }); + .get('/') + .expect(utils.shouldNotHaveHeader('ETag')) + .expect(200, done) + }) - it('should send ETag when manually set', function (done) { - var app = express(); + it('should send ETag when manually set', (done) => { + const app = express() - app.disable('etag'); + app.disable('etag') - app.use(function (req, res) { - res.set('etag', '"asdf"'); - res.send('hello!'); - }); + app.use((req, res) => { + res.set('etag', '"asdf"') + res.send('hello!') + }) request(app) - .get('/') - .expect('ETag', '"asdf"') - .expect(200, done); - }); - }); + .get('/') + .expect('ETag', '"asdf"') + .expect(200, done) + }) + }) - describe('when "strong"', function () { - it('should send strong ETag', function (done) { - var app = express(); + describe('when "strong"', () => { + it('should send strong ETag', (done) => { + const app = express() - app.set('etag', 'strong'); + app.set('etag', 'strong') - app.use(function (req, res) { - res.send('hello, world!'); - }); + app.use((req, res) => { + res.send('hello, world!') + }) request(app) - .get('/') - .expect('ETag', '"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') - .expect(200, done); + .get('/') + .expect('ETag', '"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') + .expect(200, done) }) }) - describe('when "weak"', function () { - it('should send weak ETag', function (done) { - var app = express(); + describe('when "weak"', () => { + it('should send weak ETag', (done) => { + const app = express() - app.set('etag', 'weak'); + app.set('etag', 'weak') - app.use(function (req, res) { - res.send('hello, world!'); - }); + app.use((req, res) => { + res.send('hello, world!') + }) request(app) - .get('/') - .expect('ETag', 'W/"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') - .expect(200, done) + .get('/') + .expect('ETag', 'W/"d-HwnTDHB9U/PRbFMN1z1wps51lqk"') + .expect(200, done) }) }) - describe('when a function', function () { - it('should send custom ETag', function (done) { - var app = express(); + describe('when a function', () => { + it('should send custom ETag', (done) => { + const app = express() - app.set('etag', function (body, encoding) { - var chunk = !Buffer.isBuffer(body) + app.set('etag', (body, encoding) => { + const chunk = !Buffer.isBuffer(body) ? Buffer.from(body, encoding) - : body; + : body assert.strictEqual(chunk.toString(), 'hello, world!') - return '"custom"'; - }); + return '"custom"' + }) - app.use(function (req, res) { - res.send('hello, world!'); - }); + app.use((req, res) => { + res.send('hello, world!') + }) request(app) - .get('/') - .expect('ETag', '"custom"') - .expect(200, done); + .get('/') + .expect('ETag', '"custom"') + .expect(200, done) }) - it('should not send falsy ETag', function (done) { - var app = express(); + it('should not send falsy ETag', (done) => { + const app = express() - app.set('etag', function (body, encoding) { - return undefined; - }); + app.set('etag', (body, encoding) => undefined) - app.use(function (req, res) { - res.send('hello, world!'); - }); + app.use((req, res) => { + res.send('hello, world!') + }) request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('ETag')) - .expect(200, done); + .get('/') + .expect(utils.shouldNotHaveHeader('ETag')) + .expect(200, done) }) }) }) diff --git a/test/res.sendFile.js b/test/res.sendFile.js index 16eea79761e..ba1452d1bae 100644 --- a/test/res.sendFile.js +++ b/test/res.sendFile.js @@ -1,120 +1,120 @@ 'use strict' -var after = require('after'); -var assert = require('node:assert') -var AsyncLocalStorage = require('node:async_hooks').AsyncLocalStorage -const { Buffer } = require('node:buffer'); - -var express = require('../') - , request = require('supertest') -var onFinished = require('on-finished'); -var path = require('node:path'); -var fixtures = path.join(__dirname, 'fixtures'); -var utils = require('./support/utils'); - -describe('res', function(){ - describe('.sendFile(path)', function () { - it('should error missing path', function (done) { - var app = createApp(); +const after = require('after') +const assert = require('node:assert') +const { AsyncLocalStorage } = require('node:async_hooks') +const { Buffer } = require('node:buffer') + +const express = require('../') +const request = require('supertest') +const onFinished = require('on-finished') +const path = require('node:path') +const fixtures = path.join(__dirname, 'fixtures') +const utils = require('./support/utils') + +describe('res', () => { + describe('.sendFile(path)', () => { + it('should error missing path', (done) => { + const app = createApp() request(app) - .get('/') - .expect(500, /path.*required/, done); - }); + .get('/') + .expect(500, /path.*required/, done) + }) - it('should error for non-string path', function (done) { - var app = createApp(42) + it('should error for non-string path', (done) => { + const app = createApp(42) request(app) - .get('/') - .expect(500, /TypeError: path must be a string to res.sendFile/, done) + .get('/') + .expect(500, /TypeError: path must be a string to res.sendFile/, done) }) - it('should error for non-absolute path', function (done) { - var app = createApp('name.txt') + it('should error for non-absolute path', (done) => { + const app = createApp('name.txt') request(app) .get('/') .expect(500, /TypeError: path must be absolute/, done) }) - it('should transfer a file', function (done) { - var app = createApp(path.resolve(fixtures, 'name.txt')); + it('should transfer a file', (done) => { + const app = createApp(path.resolve(fixtures, 'name.txt')) request(app) - .get('/') - .expect(200, 'tobi', done); - }); + .get('/') + .expect(200, 'tobi', done) + }) - it('should transfer a file with special characters in string', function (done) { - var app = createApp(path.resolve(fixtures, '% of dogs.txt')); + it('should transfer a file with special characters in string', (done) => { + const app = createApp(path.resolve(fixtures, '% of dogs.txt')) request(app) - .get('/') - .expect(200, '20%', done); - }); + .get('/') + .expect(200, '20%', done) + }) - it('should include ETag', function (done) { - var app = createApp(path.resolve(fixtures, 'name.txt')); + it('should include ETag', (done) => { + const app = createApp(path.resolve(fixtures, 'name.txt')) request(app) - .get('/') - .expect('ETag', /^(?:W\/)?"[^"]+"$/) - .expect(200, 'tobi', done); - }); + .get('/') + .expect('ETag', /^(?:W\/)?"[^"]+"$/) + .expect(200, 'tobi', done) + }) - it('should 304 when ETag matches', function (done) { - var app = createApp(path.resolve(fixtures, 'name.txt')); + it('should 304 when ETag matches', (done) => { + const app = createApp(path.resolve(fixtures, 'name.txt')) request(app) - .get('/') - .expect('ETag', /^(?:W\/)?"[^"]+"$/) - .expect(200, 'tobi', function (err, res) { - if (err) return done(err); - var etag = res.headers.etag; - request(app) .get('/') - .set('If-None-Match', etag) - .expect(304, done); - }); - }); + .expect('ETag', /^(?:W\/)?"[^"]+"$/) + .expect(200, 'tobi', (err, res) => { + if (err) return done(err) + const etag = res.headers.etag + request(app) + .get('/') + .set('If-None-Match', etag) + .expect(304, done) + }) + }) - it('should disable the ETag function if requested', function (done) { - var app = createApp(path.resolve(fixtures, 'name.txt')).disable('etag'); + it('should disable the ETag function if requested', (done) => { + const app = createApp(path.resolve(fixtures, 'name.txt')).disable('etag') request(app) - .get('/') - .expect(handleHeaders) - .expect(200, done); + .get('/') + .expect(handleHeaders) + .expect(200, done) function handleHeaders (res) { - assert(res.headers.etag === undefined); + assert(res.headers.etag === undefined) } - }); + }) - it('should 404 for directory', function (done) { - var app = createApp(path.resolve(fixtures, 'blog')); + it('should 404 for directory', (done) => { + const app = createApp(path.resolve(fixtures, 'blog')) request(app) - .get('/') - .expect(404, done); - }); + .get('/') + .expect(404, done) + }) - it('should 404 when not found', function (done) { - var app = createApp(path.resolve(fixtures, 'does-no-exist')); + it('should 404 when not found', (done) => { + const app = createApp(path.resolve(fixtures, 'does-no-exist')) - app.use(function (req, res) { - res.statusCode = 200; - res.send('no!'); - }); + app.use((req, res) => { + res.statusCode = 200 + res.send('no!') + }) request(app) - .get('/') - .expect(404, done); - }); + .get('/') + .expect(404, done) + }) - it('should send cache-control by default', function (done) { - var app = createApp(path.resolve(__dirname, 'fixtures/name.txt')) + it('should send cache-control by default', (done) => { + const app = createApp(path.resolve(__dirname, 'fixtures/name.txt')) request(app) .get('/') @@ -122,177 +122,177 @@ describe('res', function(){ .expect(200, done) }) - it('should not serve dotfiles by default', function (done) { - var app = createApp(path.resolve(__dirname, 'fixtures/.name')) + it('should not serve dotfiles by default', (done) => { + const app = createApp(path.resolve(__dirname, 'fixtures/.name')) request(app) .get('/') .expect(404, done) }) - it('should not override manual content-types', function (done) { - var app = express(); + it('should not override manual content-types', (done) => { + const app = express() - app.use(function (req, res) { - res.contentType('application/x-bogus'); - res.sendFile(path.resolve(fixtures, 'name.txt')); - }); + app.use((req, res) => { + res.contentType('application/x-bogus') + res.sendFile(path.resolve(fixtures, 'name.txt')) + }) request(app) - .get('/') - .expect('Content-Type', 'application/x-bogus') - .end(done); + .get('/') + .expect('Content-Type', 'application/x-bogus') + .end(done) }) - it('should not error if the client aborts', function (done) { - var app = express(); - var cb = after(2, done) - var error = null + it('should not error if the client aborts', (done) => { + const app = express() + const cb = after(2, done) + let error = null - app.use(function (req, res) { - setImmediate(function () { - res.sendFile(path.resolve(fixtures, 'name.txt')); - setTimeout(function () { + app.use((req, res) => { + setImmediate(() => { + res.sendFile(path.resolve(fixtures, 'name.txt')) + setTimeout(() => { cb(error) }, 10) }) test.req.abort() - }); + }) - app.use(function (err, req, res, next) { + app.use((err, req, res, next) => { error = err next(err) - }); + }) - var server = app.listen() - var test = request(server).get('/') - test.end(function (err) { + const server = app.listen() + const test = request(server).get('/') + test.end((err) => { assert.ok(err) server.close(cb) }) }) }) - describe('.sendFile(path, fn)', function () { - it('should invoke the callback when complete', function (done) { - var cb = after(2, done); - var app = createApp(path.resolve(fixtures, 'name.txt'), cb); + describe('.sendFile(path, fn)', () => { + it('should invoke the callback when complete', (done) => { + const cb = after(2, done) + const app = createApp(path.resolve(fixtures, 'name.txt'), cb) request(app) - .get('/') - .expect(200, cb); + .get('/') + .expect(200, cb) }) - it('should invoke the callback when client aborts', function (done) { - var cb = after(2, done) - var app = express(); + it('should invoke the callback when client aborts', (done) => { + const cb = after(2, done) + const app = express() - app.use(function (req, res) { - setImmediate(function () { - res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) { + app.use((req, res) => { + setImmediate(() => { + res.sendFile(path.resolve(fixtures, 'name.txt'), (err) => { assert.ok(err) assert.strictEqual(err.code, 'ECONNABORTED') cb() - }); - }); + }) + }) test.req.abort() - }); + }) - var server = app.listen() - var test = request(server).get('/') - test.end(function (err) { + const server = app.listen() + const test = request(server).get('/') + test.end((err) => { assert.ok(err) server.close(cb) }) }) - it('should invoke the callback when client already aborted', function (done) { - var cb = after(2, done) - var app = express(); + it('should invoke the callback when client already aborted', (done) => { + const cb = after(2, done) + const app = express() - app.use(function (req, res) { - onFinished(res, function () { - res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) { + app.use((req, res) => { + onFinished(res, () => { + res.sendFile(path.resolve(fixtures, 'name.txt'), (err) => { assert.ok(err) assert.strictEqual(err.code, 'ECONNABORTED') cb() - }); - }); + }) + }) test.req.abort() - }); + }) - var server = app.listen() - var test = request(server).get('/') - test.end(function (err) { + const server = app.listen() + const test = request(server).get('/') + test.end((err) => { assert.ok(err) server.close(cb) }) }) - it('should invoke the callback without error when HEAD', function (done) { - var app = express(); - var cb = after(2, done); + it('should invoke the callback without error when HEAD', (done) => { + const app = express() + const cb = after(2, done) - app.use(function (req, res) { - res.sendFile(path.resolve(fixtures, 'name.txt'), cb); - }); + app.use((req, res) => { + res.sendFile(path.resolve(fixtures, 'name.txt'), cb) + }) request(app) - .head('/') - .expect(200, cb); - }); + .head('/') + .expect(200, cb) + }) - it('should invoke the callback without error when 304', function (done) { - var app = express(); - var cb = after(3, done); + it('should invoke the callback without error when 304', (done) => { + const app = express() + const cb = after(3, done) - app.use(function (req, res) { - res.sendFile(path.resolve(fixtures, 'name.txt'), cb); - }); + app.use((req, res) => { + res.sendFile(path.resolve(fixtures, 'name.txt'), cb) + }) request(app) - .get('/') - .expect('ETag', /^(?:W\/)?"[^"]+"$/) - .expect(200, 'tobi', function (err, res) { - if (err) return cb(err); - var etag = res.headers.etag; - request(app) .get('/') - .set('If-None-Match', etag) - .expect(304, cb); - }); - }); + .expect('ETag', /^(?:W\/)?"[^"]+"$/) + .expect(200, 'tobi', (err, res) => { + if (err) return cb(err) + const etag = res.headers.etag + request(app) + .get('/') + .set('If-None-Match', etag) + .expect(304, cb) + }) + }) - it('should invoke the callback on 404', function(done){ - var app = express(); + it('should invoke the callback on 404', (done) => { + const app = express() - app.use(function (req, res) { - res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) { + app.use((req, res) => { + res.sendFile(path.resolve(fixtures, 'does-not-exist'), (err) => { res.send(err ? 'got ' + err.status + ' error' : 'no error') - }); - }); + }) + }) request(app) .get('/') .expect(200, 'got 404 error', done) }) - describe('async local storage', function () { - it('should persist store', function (done) { - var app = express() - var cb = after(2, done) - var store = { foo: 'bar' } + describe('async local storage', () => { + it('should persist store', (done) => { + const app = express() + const cb = after(2, done) + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) - app.use(function (req, res) { - res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) { + app.use((req, res) => { + res.sendFile(path.resolve(fixtures, 'name.txt'), (err) => { if (err) return cb(err) - var local = req.asyncLocalStorage.getStore() + const local = req.asyncLocalStorage.getStore() assert.strictEqual(local.foo, 'bar') cb() @@ -305,18 +305,18 @@ describe('res', function(){ .expect(200, 'tobi', cb) }) - it('should persist store on error', function (done) { - var app = express() - var store = { foo: 'bar' } + it('should persist store on error', (done) => { + const app = express() + const store = { foo: 'bar' } - app.use(function (req, res, next) { + app.use((req, res, next) => { req.asyncLocalStorage = new AsyncLocalStorage() req.asyncLocalStorage.run(store, next) }) - app.use(function (req, res) { - res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) { - var local = req.asyncLocalStorage.getStore() + app.use((req, res) => { + res.sendFile(path.resolve(fixtures, 'does-not-exist'), (err) => { + const local = req.asyncLocalStorage.getStore() if (local) { res.setHeader('x-store-foo', String(local.foo)) @@ -336,19 +336,19 @@ describe('res', function(){ }) }) - describe('.sendFile(path, options)', function () { - it('should pass options to send module', function (done) { + describe('.sendFile(path, options)', () => { + it('should pass options to send module', (done) => { request(createApp(path.resolve(fixtures, 'name.txt'), { start: 0, end: 1 })) - .get('/') - .expect(200, 'to', done) + .get('/') + .expect(200, 'to', done) }) - describe('with "acceptRanges" option', function () { - describe('when true', function () { - it('should advertise byte range accepted', function (done) { - var app = express() + describe('with "acceptRanges" option', () => { + describe('when true', () => { + it('should advertise byte range accepted', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'nums.txt'), { acceptRanges: true }) @@ -362,10 +362,10 @@ describe('res', function(){ .end(done) }) - it('should respond to range request', function (done) { - var app = express() + it('should respond to range request', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'nums.txt'), { acceptRanges: true }) @@ -378,11 +378,11 @@ describe('res', function(){ }) }) - describe('when false', function () { - it('should not advertise accept-ranges', function (done) { - var app = express() + describe('when false', () => { + it('should not advertise accept-ranges', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'nums.txt'), { acceptRanges: false }) @@ -395,10 +395,10 @@ describe('res', function(){ .end(done) }) - it('should not honor range requests', function (done) { - var app = express() + it('should not honor range requests', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'nums.txt'), { acceptRanges: false }) @@ -412,12 +412,12 @@ describe('res', function(){ }) }) - describe('with "cacheControl" option', function () { - describe('when true', function () { - it('should send cache-control header', function (done) { - var app = express() + describe('with "cacheControl" option', () => { + describe('when true', () => { + it('should send cache-control header', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { cacheControl: true }) @@ -431,11 +431,11 @@ describe('res', function(){ }) }) - describe('when false', function () { - it('should not send cache-control header', function (done) { - var app = express() + describe('when false', () => { + it('should not send cache-control header', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { cacheControl: false }) @@ -450,12 +450,12 @@ describe('res', function(){ }) }) - describe('with "dotfiles" option', function () { - describe('when "allow"', function () { - it('should allow dotfiles', function (done) { - var app = express() + describe('with "dotfiles" option', () => { + describe('when "allow"', () => { + it('should allow dotfiles', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, '.name'), { dotfiles: 'allow' }) @@ -469,11 +469,11 @@ describe('res', function(){ }) }) - describe('when "deny"', function () { - it('should deny dotfiles', function (done) { - var app = express() + describe('when "deny"', () => { + it('should deny dotfiles', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, '.name'), { dotfiles: 'deny' }) @@ -487,11 +487,11 @@ describe('res', function(){ }) }) - describe('when "ignore"', function () { - it('should ignore dotfiles', function (done) { - var app = express() + describe('when "ignore"', () => { + it('should ignore dotfiles', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, '.name'), { dotfiles: 'ignore' }) @@ -506,11 +506,11 @@ describe('res', function(){ }) }) - describe('with "headers" option', function () { - it('should set headers on response', function (done) { - var app = express() + describe('with "headers" option', () => { + it('should set headers on response', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { headers: { 'X-Foo': 'Bar', @@ -527,10 +527,10 @@ describe('res', function(){ .end(done) }) - it('should use last header when duplicated', function (done) { - var app = express() + it('should use last header when duplicated', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { headers: { 'X-Foo': 'Bar', @@ -546,10 +546,10 @@ describe('res', function(){ .end(done) }) - it('should override Content-Type', function (done) { - var app = express() + it('should override Content-Type', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { headers: { 'Content-Type': 'text/x-custom' @@ -564,10 +564,10 @@ describe('res', function(){ .end(done) }) - it('should not set headers on 404', function (done) { - var app = express() + it('should not set headers on 404', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'does-not-exist'), { headers: { 'X-Foo': 'Bar' @@ -583,12 +583,12 @@ describe('res', function(){ }) }) - describe('with "immutable" option', function () { - describe('when true', function () { - it('should send cache-control header with immutable', function (done) { - var app = express() + describe('with "immutable" option', () => { + describe('when true', () => { + it('should send cache-control header with immutable', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { immutable: true }) @@ -602,11 +602,11 @@ describe('res', function(){ }) }) - describe('when false', function () { - it('should not send cache-control header with immutable', function (done) { - var app = express() + describe('when false', () => { + it('should not send cache-control header with immutable', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { immutable: false }) @@ -621,12 +621,12 @@ describe('res', function(){ }) }) - describe('with "lastModified" option', function () { - describe('when true', function () { - it('should send last-modified header', function (done) { - var app = express() + describe('with "lastModified" option', () => { + describe('when true', () => { + it('should send last-modified header', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { lastModified: true }) @@ -639,10 +639,10 @@ describe('res', function(){ .end(done) }) - it('should conditionally respond with if-modified-since', function (done) { - var app = express() + it('should conditionally respond with if-modified-since', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { lastModified: true }) @@ -655,11 +655,11 @@ describe('res', function(){ }) }) - describe('when false', function () { - it('should not have last-modified header', function (done) { - var app = express() + describe('when false', () => { + it('should not have last-modified header', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { lastModified: false }) @@ -672,10 +672,10 @@ describe('res', function(){ .end(done) }) - it('should not honor if-modified-since', function (done) { - var app = express() + it('should not honor if-modified-since', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { lastModified: false }) @@ -691,11 +691,11 @@ describe('res', function(){ }) }) - describe('with "maxAge" option', function () { - it('should set cache-control max-age to milliseconds', function (done) { - var app = express() + describe('with "maxAge" option', () => { + it('should set cache-control max-age to milliseconds', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: 20000 }) @@ -708,10 +708,10 @@ describe('res', function(){ .end(done) }) - it('should cap cache-control max-age to 1 year', function (done) { - var app = express() + it('should cap cache-control max-age to 1 year', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: 99999999999 }) @@ -724,10 +724,10 @@ describe('res', function(){ .end(done) }) - it('should min cache-control max-age to 0', function (done) { - var app = express() + it('should min cache-control max-age to 0', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: -20000 }) @@ -740,10 +740,10 @@ describe('res', function(){ .end(done) }) - it('should floor cache-control max-age', function (done) { - var app = express() + it('should floor cache-control max-age', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: 21911.23 }) @@ -756,11 +756,11 @@ describe('res', function(){ .end(done) }) - describe('when cacheControl: false', function () { - it('should not send cache-control', function (done) { - var app = express() + describe('when cacheControl: false', () => { + it('should not send cache-control', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { cacheControl: false, maxAge: 20000 @@ -775,11 +775,11 @@ describe('res', function(){ }) }) - describe('when string', function () { - it('should accept plain number as milliseconds', function (done) { - var app = express() + describe('when string', () => { + it('should accept plain number as milliseconds', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: '20000' }) @@ -792,10 +792,10 @@ describe('res', function(){ .end(done) }) - it('should accept suffix "s" for seconds', function (done) { - var app = express() + it('should accept suffix "s" for seconds', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: '20s' }) @@ -808,10 +808,10 @@ describe('res', function(){ .end(done) }) - it('should accept suffix "m" for minutes', function (done) { - var app = express() + it('should accept suffix "m" for minutes', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: '20m' }) @@ -824,10 +824,10 @@ describe('res', function(){ .end(done) }) - it('should accept suffix "d" for days', function (done) { - var app = express() + it('should accept suffix "d" for days', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile(path.resolve(fixtures, 'user.html'), { maxAge: '20d' }) @@ -842,11 +842,11 @@ describe('res', function(){ }) }) - describe('with "root" option', function () { - it('should allow relative path', function (done) { - var app = express() + describe('with "root" option', () => { + it('should allow relative path', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile('name.txt', { root: fixtures }) @@ -857,10 +857,10 @@ describe('res', function(){ .expect(200, 'tobi', done) }) - it('should allow up within root', function (done) { - var app = express() + it('should allow up within root', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile('fake/../name.txt', { root: fixtures }) @@ -871,10 +871,10 @@ describe('res', function(){ .expect(200, 'tobi', done) }) - it('should reject up outside root', function (done) { - var app = express() + it('should reject up outside root', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile('..' + path.sep + path.relative(path.dirname(fixtures), path.join(fixtures, 'name.txt')), { root: fixtures }) @@ -885,10 +885,10 @@ describe('res', function(){ .expect(403, done) }) - it('should reject reading outside root', function (done) { - var app = express() + it('should reject reading outside root', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendFile('../name.txt', { root: fixtures }) @@ -902,12 +902,12 @@ describe('res', function(){ }) }) -function createApp(path, options, fn) { - var app = express(); +function createApp (path, options, fn) { + const app = express() - app.use(function (req, res) { - res.sendFile(path, options, fn); - }); + app.use((req, res) => { + res.sendFile(path, options, fn) + }) - return app; + return app } diff --git a/test/res.sendStatus.js b/test/res.sendStatus.js index b244cf9d173..56b2f22e983 100644 --- a/test/res.sendStatus.js +++ b/test/res.sendStatus.js @@ -1,38 +1,38 @@ 'use strict' -var express = require('..') -var request = require('supertest') +const express = require('../') +const request = require('supertest') -describe('res', function () { - describe('.sendStatus(statusCode)', function () { - it('should send the status code and message as body', function (done) { - var app = express(); +describe('res', () => { + describe('.sendStatus(statusCode)', () => { + it('should send the status code and message as body', (done) => { + const app = express() - app.use(function(req, res){ - res.sendStatus(201); - }); + app.use((req, res) => { + res.sendStatus(201) + }) request(app) - .get('/') - .expect(201, 'Created', done); + .get('/') + .expect(201, 'Created', done) }) - it('should work with unknown code', function (done) { - var app = express(); + it('should work with unknown code', (done) => { + const app = express() - app.use(function(req, res){ - res.sendStatus(599); - }); + app.use((req, res) => { + res.sendStatus(599) + }) request(app) - .get('/') - .expect(599, '599', done); + .get('/') + .expect(599, '599', done) }) - it('should raise error for invalid status code', function (done) { - var app = express() + it('should raise error for invalid status code', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.sendStatus(undefined).end() }) diff --git a/test/res.set.js b/test/res.set.js index 04511c1c95f..6bacdc8644c 100644 --- a/test/res.set.js +++ b/test/res.set.js @@ -1,124 +1,124 @@ 'use strict' -var express = require('..'); -var request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('res', function(){ - describe('.set(field, value)', function(){ - it('should set the response header field', function(done){ - var app = express(); +describe('res', () => { + describe('.set(field, value)', () => { + it('should set the response header field', (done) => { + const app = express() - app.use(function(req, res){ - res.set('Content-Type', 'text/x-foo; charset=utf-8').end(); - }); + app.use((req, res) => { + res.set('Content-Type', 'text/x-foo; charset=utf-8').end() + }) request(app) - .get('/') - .expect('Content-Type', 'text/x-foo; charset=utf-8') - .end(done); + .get('/') + .expect('Content-Type', 'text/x-foo; charset=utf-8') + .end(done) }) - it('should coerce to a string', function (done) { - var app = express(); + it('should coerce to a string', (done) => { + const app = express() - app.use(function (req, res) { - res.set('X-Number', 123); - res.end(typeof res.get('X-Number')); - }); + app.use((req, res) => { + res.set('X-Number', 123) + res.end(typeof res.get('X-Number')) + }) request(app) - .get('/') - .expect('X-Number', '123') - .expect(200, 'string', done); + .get('/') + .expect('X-Number', '123') + .expect(200, 'string', done) }) }) - describe('.set(field, values)', function(){ - it('should set multiple response header fields', function(done){ - var app = express(); + describe('.set(field, values)', () => { + it('should set multiple response header fields', (done) => { + const app = express() - app.use(function(req, res){ - res.set('Set-Cookie', ["type=ninja", "language=javascript"]); - res.send(res.get('Set-Cookie')); - }); + app.use((req, res) => { + res.set('Set-Cookie', ['type=ninja', 'language=javascript']) + res.send(res.get('Set-Cookie')) + }) request(app) - .get('/') - .expect('["type=ninja","language=javascript"]', done); + .get('/') + .expect('["type=ninja","language=javascript"]', done) }) - it('should coerce to an array of strings', function (done) { - var app = express(); + it('should coerce to an array of strings', (done) => { + const app = express() - app.use(function (req, res) { - res.set('X-Numbers', [123, 456]); - res.end(JSON.stringify(res.get('X-Numbers'))); - }); + app.use((req, res) => { + res.set('X-Numbers', [123, 456]) + res.end(JSON.stringify(res.get('X-Numbers'))) + }) request(app) - .get('/') - .expect('X-Numbers', '123, 456') - .expect(200, '["123","456"]', done); + .get('/') + .expect('X-Numbers', '123, 456') + .expect(200, '["123","456"]', done) }) - it('should not set a charset of one is already set', function (done) { - var app = express(); + it('should not set a charset of one is already set', (done) => { + const app = express() - app.use(function (req, res) { - res.set('Content-Type', 'text/html; charset=lol'); - res.end(); - }); + app.use((req, res) => { + res.set('Content-Type', 'text/html; charset=lol') + res.end() + }) request(app) - .get('/') - .expect('Content-Type', 'text/html; charset=lol') - .expect(200, done); + .get('/') + .expect('Content-Type', 'text/html; charset=lol') + .expect(200, done) }) - it('should throw when Content-Type is an array', function (done) { - var app = express() + it('should throw when Content-Type is an array', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.set('Content-Type', ['text/html']) res.end() - }); + }) request(app) - .get('/') - .expect(500, /TypeError: Content-Type cannot be set to an Array/, done) + .get('/') + .expect(500, /TypeError: Content-Type cannot be set to an Array/, done) }) }) - describe('.set(object)', function(){ - it('should set multiple fields', function(done){ - var app = express(); + describe('.set(object)', () => { + it('should set multiple fields', (done) => { + const app = express() - app.use(function(req, res){ + app.use((req, res) => { res.set({ 'X-Foo': 'bar', 'X-Bar': 'baz' - }).end(); - }); + }).end() + }) request(app) - .get('/') - .expect('X-Foo', 'bar') - .expect('X-Bar', 'baz') - .end(done); + .get('/') + .expect('X-Foo', 'bar') + .expect('X-Bar', 'baz') + .end(done) }) - it('should coerce to a string', function (done) { - var app = express(); + it('should coerce to a string', (done) => { + const app = express() - app.use(function (req, res) { - res.set({ 'X-Number': 123 }); - res.end(typeof res.get('X-Number')); - }); + app.use((req, res) => { + res.set({ 'X-Number': 123 }) + res.end(typeof res.get('X-Number')) + }) request(app) - .get('/') - .expect('X-Number', '123') - .expect(200, 'string', done); + .get('/') + .expect('X-Number', '123') + .expect(200, 'string', done) }) }) }) diff --git a/test/res.status.js b/test/res.status.js index 59c8a57e702..421c388594c 100644 --- a/test/res.status.js +++ b/test/res.status.js @@ -1,28 +1,27 @@ 'use strict' -const express = require('../.'); -const request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('res', function () { - describe('.status(code)', function () { +describe('res', () => { + describe('.status(code)', () => { + it('should set the status code when valid', (done) => { + const app = express() - it('should set the status code when valid', function (done) { - var app = express(); - - app.use(function (req, res) { - res.status(200).end(); - }); + app.use((req, res) => { + res.status(200).end() + }) request(app) .get('/') - .expect(200, done); - }); + .expect(200, done) + }) - describe('accept valid ranges', function() { + describe('accept valid ranges', () => { // not testing w/ 100, because that has specific meaning and behavior in Node as Expect: 100-continue - it('should set the response status code to 101', function (done) { - var app = express() + it('should set the response status code to 101', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(101).end() }) @@ -31,10 +30,10 @@ describe('res', function () { .expect(101, done) }) - it('should set the response status code to 201', function (done) { - var app = express() + it('should set the response status code to 201', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(201).end() }) @@ -43,10 +42,10 @@ describe('res', function () { .expect(201, done) }) - it('should set the response status code to 302', function (done) { - var app = express() + it('should set the response status code to 302', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(302).end() }) @@ -55,10 +54,10 @@ describe('res', function () { .expect(302, done) }) - it('should set the response status code to 403', function (done) { - var app = express() + it('should set the response status code to 403', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(403).end() }) @@ -67,10 +66,10 @@ describe('res', function () { .expect(403, done) }) - it('should set the response status code to 501', function (done) { - var app = express() + it('should set the response status code to 501', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(501).end() }) @@ -79,10 +78,10 @@ describe('res', function () { .expect(501, done) }) - it('should set the response status code to 700', function (done) { - var app = express() + it('should set the response status code to 700', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(700).end() }) @@ -91,10 +90,10 @@ describe('res', function () { .expect(700, done) }) - it('should set the response status code to 800', function (done) { - var app = express() + it('should set the response status code to 800', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(800).end() }) @@ -103,10 +102,10 @@ describe('res', function () { .expect(800, done) }) - it('should set the response status code to 900', function (done) { - var app = express() + it('should set the response status code to 900', (done) => { + const app = express() - app.use(function (req, res) { + app.use((req, res) => { res.status(900).end() }) @@ -116,91 +115,90 @@ describe('res', function () { }) }) - describe('invalid status codes', function () { - it('should raise error for status code below 100', function (done) { - var app = express(); + describe('invalid status codes', () => { + it('should raise error for status code below 100', (done) => { + const app = express() - app.use(function (req, res) { - res.status(99).end(); - }); + app.use((req, res) => { + res.status(99).end() + }) request(app) .get('/') - .expect(500, /Invalid status code/, done); - }); + .expect(500, /Invalid status code/, done) + }) - it('should raise error for status code above 999', function (done) { - var app = express(); + it('should raise error for status code above 999', (done) => { + const app = express() - app.use(function (req, res) { - res.status(1000).end(); - }); + app.use((req, res) => { + res.status(1000).end() + }) request(app) .get('/') - .expect(500, /Invalid status code/, done); - }); + .expect(500, /Invalid status code/, done) + }) - it('should raise error for non-integer status codes', function (done) { - var app = express(); + it('should raise error for non-integer status codes', (done) => { + const app = express() - app.use(function (req, res) { - res.status(200.1).end(); - }); + app.use((req, res) => { + res.status(200.1).end() + }) request(app) .get('/') - .expect(500, /Invalid status code/, done); - }); + .expect(500, /Invalid status code/, done) + }) - it('should raise error for undefined status code', function (done) { - var app = express(); + it('should raise error for undefined status code', (done) => { + const app = express() - app.use(function (req, res) { - res.status(undefined).end(); - }); + app.use((req, res) => { + res.status(undefined).end() + }) request(app) .get('/') - .expect(500, /Invalid status code/, done); - }); + .expect(500, /Invalid status code/, done) + }) - it('should raise error for null status code', function (done) { - var app = express(); + it('should raise error for null status code', (done) => { + const app = express() - app.use(function (req, res) { - res.status(null).end(); - }); + app.use((req, res) => { + res.status(null).end() + }) request(app) .get('/') - .expect(500, /Invalid status code/, done); - }); + .expect(500, /Invalid status code/, done) + }) - it('should raise error for string status code', function (done) { - var app = express(); + it('should raise error for string status code', (done) => { + const app = express() - app.use(function (req, res) { - res.status("200").end(); - }); + app.use((req, res) => { + res.status('200').end() + }) request(app) .get('/') - .expect(500, /Invalid status code/, done); - }); + .expect(500, /Invalid status code/, done) + }) - it('should raise error for NaN status code', function (done) { - var app = express(); + it('should raise error for NaN status code', (done) => { + const app = express() - app.use(function (req, res) { - res.status(NaN).end(); - }); + app.use((req, res) => { + res.status(NaN).end() + }) request(app) .get('/') - .expect(500, /Invalid status code/, done); - }); - }); - }); -}); - + .expect(500, /Invalid status code/, done) + }) + }) + }) +}) diff --git a/test/res.type.js b/test/res.type.js index 09285af3914..98d0cb3a780 100644 --- a/test/res.type.js +++ b/test/res.type.js @@ -1,46 +1,46 @@ 'use strict' -var express = require('../') - , request = require('supertest'); +const express = require('../') +const request = require('supertest') -describe('res', function(){ - describe('.type(str)', function(){ - it('should set the Content-Type based on a filename', function(done){ - var app = express(); +describe('res', () => { + describe('.type(str)', () => { + it('should set the Content-Type based on a filename', (done) => { + const app = express() - app.use(function(req, res){ - res.type('foo.js').end('var name = "tj";'); - }); + app.use((req, res) => { + res.type('foo.js').end('var name = "tj";') + }) request(app) - .get('/') - .expect('Content-Type', 'text/javascript; charset=utf-8') - .end(done) + .get('/') + .expect('Content-Type', 'text/javascript; charset=utf-8') + .end(done) }) - it('should default to application/octet-stream', function(done){ - var app = express(); + it('should default to application/octet-stream', (done) => { + const app = express() - app.use(function(req, res){ - res.type('rawr').end('var name = "tj";'); - }); + app.use((req, res) => { + res.type('rawr').end('var name = "tj";') + }) request(app) - .get('/') - .expect('Content-Type', 'application/octet-stream', done); + .get('/') + .expect('Content-Type', 'application/octet-stream', done) }) - it('should set the Content-Type with type/subtype', function(done){ - var app = express(); + it('should set the Content-Type with type/subtype', (done) => { + const app = express() - app.use(function(req, res){ + app.use((req, res) => { res.type('application/vnd.amazon.ebook') - .end('var name = "tj";'); - }); + .end('var name = "tj";') + }) request(app) - .get('/') - .expect('Content-Type', 'application/vnd.amazon.ebook', done); + .get('/') + .expect('Content-Type', 'application/vnd.amazon.ebook', done) }) }) }) diff --git a/test/res.vary.js b/test/res.vary.js index ff3c9716529..9aab950461c 100644 --- a/test/res.vary.js +++ b/test/res.vary.js @@ -1,90 +1,90 @@ 'use strict' -var express = require('..'); -var request = require('supertest'); -var utils = require('./support/utils'); +const express = require('../') +const request = require('supertest') +const utils = require('./support/utils') -describe('res.vary()', function(){ - describe('with no arguments', function(){ - it('should throw error', function (done) { - var app = express(); +describe('res.vary()', () => { + describe('with no arguments', () => { + it('should throw error', (done) => { + const app = express() - app.use(function (req, res) { - res.vary(); - res.end(); - }); + app.use((req, res) => { + res.vary() + res.end() + }) request(app) - .get('/') - .expect(500, /field.*required/, done) + .get('/') + .expect(500, /field.*required/, done) }) }) - describe('with an empty array', function(){ - it('should not set Vary', function (done) { - var app = express(); + describe('with an empty array', () => { + it('should not set Vary', (done) => { + const app = express() - app.use(function (req, res) { - res.vary([]); - res.end(); - }); + app.use((req, res) => { + res.vary([]) + res.end() + }) request(app) - .get('/') - .expect(utils.shouldNotHaveHeader('Vary')) - .expect(200, done); + .get('/') + .expect(utils.shouldNotHaveHeader('Vary')) + .expect(200, done) }) }) - describe('with an array', function(){ - it('should set the values', function (done) { - var app = express(); + describe('with an array', () => { + it('should set the values', (done) => { + const app = express() - app.use(function (req, res) { - res.vary(['Accept', 'Accept-Language', 'Accept-Encoding']); - res.end(); - }); + app.use((req, res) => { + res.vary(['Accept', 'Accept-Language', 'Accept-Encoding']) + res.end() + }) request(app) - .get('/') - .expect('Vary', 'Accept, Accept-Language, Accept-Encoding') - .expect(200, done); + .get('/') + .expect('Vary', 'Accept, Accept-Language, Accept-Encoding') + .expect(200, done) }) }) - describe('with a string', function(){ - it('should set the value', function (done) { - var app = express(); + describe('with a string', () => { + it('should set the value', (done) => { + const app = express() - app.use(function (req, res) { - res.vary('Accept'); - res.end(); - }); + app.use((req, res) => { + res.vary('Accept') + res.end() + }) request(app) - .get('/') - .expect('Vary', 'Accept') - .expect(200, done); + .get('/') + .expect('Vary', 'Accept') + .expect(200, done) }) }) - describe('when the value is present', function(){ - it('should not add it again', function (done) { - var app = express(); + describe('when the value is present', () => { + it('should not add it again', (done) => { + const app = express() - app.use(function (req, res) { - res.vary('Accept'); - res.vary('Accept-Encoding'); - res.vary('Accept-Encoding'); - res.vary('Accept-Encoding'); - res.vary('Accept'); - res.end(); - }); + app.use((req, res) => { + res.vary('Accept') + res.vary('Accept-Encoding') + res.vary('Accept-Encoding') + res.vary('Accept-Encoding') + res.vary('Accept') + res.end() + }) request(app) - .get('/') - .expect('Vary', 'Accept, Accept-Encoding') - .expect(200, done); + .get('/') + .expect('Vary', 'Accept, Accept-Encoding') + .expect(200, done) }) }) }) diff --git a/test/support/env.js b/test/support/env.js index 000638ceeae..c967199232e 100644 --- a/test/support/env.js +++ b/test/support/env.js @@ -1,3 +1,2 @@ - -process.env.NODE_ENV = 'test'; -process.env.NO_DEPRECATION = 'body-parser,express'; +process.env.NODE_ENV = 'test' +process.env.NO_DEPRECATION = 'body-parser,express' diff --git a/test/support/tmpl.js b/test/support/tmpl.js index e24b6fe773b..f26cb85583c 100644 --- a/test/support/tmpl.js +++ b/test/support/tmpl.js @@ -1,36 +1,36 @@ -var fs = require('node:fs'); +const fs = require('node:fs') -var variableRegExp = /\$([0-9a-zA-Z\.]+)/g; +const variableRegExp = /\$([0-9a-zA-Z.]+)/g -module.exports = function renderFile(fileName, options, callback) { - function onReadFile(err, str) { +module.exports = function renderFile (fileName, options, callback) { + function onReadFile (err, str) { if (err) { - callback(err); - return; + callback(err) + return } try { - str = str.replace(variableRegExp, generateVariableLookup(options)); + str = str.replace(variableRegExp, generateVariableLookup(options)) } catch (e) { - err = e; + err = e err.name = 'RenderError' } - callback(err, str); + callback(err, str) } - fs.readFile(fileName, 'utf8', onReadFile); -}; + fs.readFile(fileName, 'utf8', onReadFile) +} -function generateVariableLookup(data) { - return function variableLookup(str, path) { - var parts = path.split('.'); - var value = data; +function generateVariableLookup (data) { + return function variableLookup (str, path) { + const parts = path.split('.') + let value = data - for (var i = 0; i < parts.length; i++) { - value = value[parts[i]]; + for (let i = 0; i < parts.length; i++) { + value = value[parts[i]] } - return value; - }; + return value + } } diff --git a/test/support/utils.js b/test/support/utils.js index fb816b08000..891846eb4aa 100644 --- a/test/support/utils.js +++ b/test/support/utils.js @@ -1,11 +1,10 @@ - /** * Module dependencies. * @private */ -var assert = require('node:assert'); -const { Buffer } = require('node:buffer'); +const assert = require('node:assert') +const { Buffer } = require('node:buffer') /** * Module exports. @@ -15,7 +14,7 @@ const { Buffer } = require('node:buffer'); exports.shouldHaveBody = shouldHaveBody exports.shouldHaveHeader = shouldHaveHeader exports.shouldNotHaveBody = shouldNotHaveBody -exports.shouldNotHaveHeader = shouldNotHaveHeader; +exports.shouldNotHaveHeader = shouldNotHaveHeader exports.shouldSkipQuery = shouldSkipQuery /** @@ -27,7 +26,7 @@ exports.shouldSkipQuery = shouldSkipQuery function shouldHaveBody (buf) { return function (res) { - var body = !Buffer.isBuffer(res.body) + const body = !Buffer.isBuffer(res.body) ? Buffer.from(res.text) : res.body assert.ok(body, 'response has body') @@ -66,21 +65,20 @@ function shouldNotHaveBody () { * @param {string} header Header name to check * @returns {function} */ -function shouldNotHaveHeader(header) { +function shouldNotHaveHeader (header) { return function (res) { - assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header); - }; + assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header) + } } -function getMajorVersion(versionString) { - return versionString.split('.')[0]; +function getMajorVersion (versionString) { + return versionString.split('.')[0] } -function shouldSkipQuery(versionString) { +function shouldSkipQuery (versionString) { // Skipping HTTP QUERY tests below Node 22, QUERY wasn't fully supported by Node until 22 // we could update this implementation to run on supported versions of 21 once they exist // upstream tracking https://github.com/nodejs/node/issues/51562 // express tracking issue: https://github.com/expressjs/express/issues/5615 return Number(getMajorVersion(versionString)) < 22 } - diff --git a/test/utils.js b/test/utils.js index 1c06036aa98..654fec42615 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,26 +1,26 @@ 'use strict' -var assert = require('node:assert'); -const { Buffer } = require('node:buffer'); -var utils = require('../lib/utils'); +const assert = require('node:assert') +const { Buffer } = require('node:buffer') +const utils = require('../lib/utils') -describe('utils.etag(body, encoding)', function(){ - it('should support strings', function(){ +describe('utils.etag(body, encoding)', () => { + it('should support strings', () => { assert.strictEqual(utils.etag('express!'), '"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') }) - it('should support utf8 strings', function(){ + it('should support utf8 strings', () => { assert.strictEqual(utils.etag('express❤', 'utf8'), '"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"') }) - it('should support buffer', function(){ + it('should support buffer', () => { assert.strictEqual(utils.etag(Buffer.from('express!')), '"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') }) - it('should support empty string', function(){ + it('should support empty string', () => { assert.strictEqual(utils.etag(''), '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') }) @@ -28,55 +28,54 @@ describe('utils.etag(body, encoding)', function(){ describe('utils.normalizeType acceptParams method', () => { it('should handle a type with a malformed parameter and break the loop in acceptParams', () => { - const result = utils.normalizeType('text/plain;invalid'); - assert.deepEqual(result,{ + const result = utils.normalizeType('text/plain;invalid') + assert.deepEqual(result, { value: 'text/plain', quality: 1, params: {} // No parameters are added since "invalid" has no "=" - }); - }); -}); - + }) + }) +}) -describe('utils.setCharset(type, charset)', function () { - it('should do anything without type', function () { - assert.strictEqual(utils.setCharset(), undefined); - }); +describe('utils.setCharset(type, charset)', () => { + it('should do anything without type', () => { + assert.strictEqual(utils.setCharset(), undefined) + }) - it('should return type if not given charset', function () { - assert.strictEqual(utils.setCharset('text/html'), 'text/html'); - }); + it('should return type if not given charset', () => { + assert.strictEqual(utils.setCharset('text/html'), 'text/html') + }) - it('should keep charset if not given charset', function () { - assert.strictEqual(utils.setCharset('text/html; charset=utf-8'), 'text/html; charset=utf-8'); - }); + it('should keep charset if not given charset', () => { + assert.strictEqual(utils.setCharset('text/html; charset=utf-8'), 'text/html; charset=utf-8') + }) - it('should set charset', function () { - assert.strictEqual(utils.setCharset('text/html', 'utf-8'), 'text/html; charset=utf-8'); - }); + it('should set charset', () => { + assert.strictEqual(utils.setCharset('text/html', 'utf-8'), 'text/html; charset=utf-8') + }) - it('should override charset', function () { - assert.strictEqual(utils.setCharset('text/html; charset=iso-8859-1', 'utf-8'), 'text/html; charset=utf-8'); - }); -}); + it('should override charset', () => { + assert.strictEqual(utils.setCharset('text/html; charset=iso-8859-1', 'utf-8'), 'text/html; charset=utf-8') + }) +}) -describe('utils.wetag(body, encoding)', function(){ - it('should support strings', function(){ +describe('utils.wetag(body, encoding)', () => { + it('should support strings', () => { assert.strictEqual(utils.wetag('express!'), 'W/"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') }) - it('should support utf8 strings', function(){ + it('should support utf8 strings', () => { assert.strictEqual(utils.wetag('express❤', 'utf8'), 'W/"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"') }) - it('should support buffer', function(){ + it('should support buffer', () => { assert.strictEqual(utils.wetag(Buffer.from('express!')), 'W/"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"') }) - it('should support empty string', function(){ + it('should support empty string', () => { assert.strictEqual(utils.wetag(''), 'W/"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"') })