web-service acceptance tests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by TJ Holowaychuk · committed by TJ Holowaychuk · parent 1ea221a · Browse files · 3 files·+163 added−121 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+163 added−121 removed
- tests:+48 added−0 removed
- other:+115 added−121 removed
Provenance
- Commit
f6ca25e- Tree
34c3ec8- Author
TJ Holowaychuk <tj@vision-media.ca>- Committer
TJ Holowaychuk <tj@vision-media.ca>- Parent
1ea221a
3 files changed+163 added−121 removed
deleted:examples/web-service/app.js-121 removed
1-2-/**3- * Module dependencies.4- */5-6-var express = require('../../lib/express');7-8-var app = express.createServer();9-10-// configuration11-12-// if we wanted to supply more than JSON, we could13-// use something similar to the content-negotiation14-// example.15-16-// here we validate the API key,17-// by mounting this middleware to /api/v118-// meaning only paths prefixed with "/api/v1"19-// will cause this middleware to be invoked20-21-app.use('/api/v1', function(req, res, next){22- var key = req.query['api-key'];23-24- // key isnt present25- if (!key) return next(new Error('api key required'));26-27- // key is invalid28- if (!~apiKeys.indexOf(key)) return next(new Error('invalid api key'));29-30- // all good, store req.key for route access31- req.key = key;32- next();33-});34-35-// position our routes above the error handling middleware,36-// and below our API middleware, since we want the API validation37-// to take place BEFORE our routes38-app.use(app.router);39-40-// middleware with an arity of 4 are considered41-// error handling middleware. When you next(err)42-// it will be passed through the defined middleware43-// in order, but ONLY those with an arity of 4, ignoring44-// regular middleware.45-app.use(function(err, req, res, next){46- // whatever you want here, feel free to populate47- // properties on `err` to treat it differently in here,48- // or when you next(err) set res.statusCode= etc.49- res.send(500, { error: err.message });50-});51-52-// our custom JSON 404 middleware. Since it's placed last53-// it will be the last middleware called, if all others54-// invoke next() and do not respond.55-app.use(function(req, res){56- res.send(404, { error: "Lame, can't find that" });57-});58-59-/**60- * Generate our unique identifier.61- */62-63-function uid() {64- return [65- Math.random() * 0xffff | 066- , Math.random() * 0xffff | 067- , Math.random() * 0xffff | 068- , Date.now()69- ].join('-');70-}71-72-// map of valid api keys, typically mapped to73-// account info with some sort of database like redis.74-// api keys do _not_ serve as authentication, merely to75-// track API usage or help prevent malicious behavior etc.76-77-var apiKeys = [uid(), uid(), uid()];78-79-console.log('valid keys:\n ', apiKeys.join('\n '));80-81-// these two objects will serve as our faux database82-83-var repos = [84- { name: 'express', url: 'http://github.com/visionmedia/express' }85- , { name: 'stylus', url: 'http://github.com/learnboost/stylus' }86- , { name: 'cluster', url: 'http://github.com/learnboost/cluster' }87-];88-89-var users = [90- { name: 'tobi' }91- , { name: 'loki' }92- , { name: 'jane' }93-];94-95-var userRepos = {96- tobi: [repos[0], repos[1]]97- , loki: [repos[1]]98- , jane: [repos[2]]99-};100-101-// we now can assume the api key is valid,102-// and simply expose the data103-104-app.get('/api/v1/users', function(req, res, next){105- res.send(users);106-});107-108-app.get('/api/v1/repos', function(req, res, next){109- res.send(repos);110-});111-112-app.get('/api/v1/user/:name/repos', function(req, res, next){113- var name = req.params.name114- , user = userRepos[name];115- 116- if (user) res.send(user);117- else next();118-});119-120-app.listen(3000);121-console.log('Express server listening on port 3000');added:examples/web-service/index.js+115 added
1+2+/**3+ * Module dependencies.4+ */5+6+var express = require('../../');7+8+var app = module.exports = express();9+10+// create an error with .status. we11+// can then use the property in our12+// custom error handler (Connect repects this prop as well)13+14+function error(status, msg) {15+ var err = new Error(msg);16+ err.status = status;17+ return err;18+}19+20+// if we wanted to supply more than JSON, we could21+// use something similar to the content-negotiation22+// example.23+24+// here we validate the API key,25+// by mounting this middleware to /api26+// meaning only paths prefixed with "/api"27+// will cause this middleware to be invoked28+29+app.use('/api', function(req, res, next){30+ var key = req.query['api-key'];31+32+ // key isnt present33+ if (!key) return next(error(400, 'api key required'));34+35+ // key is invalid36+ if (!~apiKeys.indexOf(key)) return next(error(401, 'invalid api key'));37+38+ // all good, store req.key for route access39+ req.key = key;40+ next();41+});42+43+// position our routes above the error handling middleware,44+// and below our API middleware, since we want the API validation45+// to take place BEFORE our routes46+app.use(app.router);47+48+// middleware with an arity of 4 are considered49+// error handling middleware. When you next(err)50+// it will be passed through the defined middleware51+// in order, but ONLY those with an arity of 4, ignoring52+// regular middleware.53+app.use(function(err, req, res, next){54+ // whatever you want here, feel free to populate55+ // properties on `err` to treat it differently in here.56+ res.send(err.status || 500, { error: err.message });57+});58+59+// our custom JSON 404 middleware. Since it's placed last60+// it will be the last middleware called, if all others61+// invoke next() and do not respond.62+app.use(function(req, res){63+ res.send(404, { error: "Lame, can't find that" });64+});65+66+// map of valid api keys, typically mapped to67+// account info with some sort of database like redis.68+// api keys do _not_ serve as authentication, merely to69+// track API usage or help prevent malicious behavior etc.70+71+var apiKeys = ['foo', 'bar', 'baz'];72+73+// these two objects will serve as our faux database74+75+var repos = [76+ { name: 'express', url: 'http://github.com/visionmedia/express' }77+ , { name: 'stylus', url: 'http://github.com/learnboost/stylus' }78+ , { name: 'cluster', url: 'http://github.com/learnboost/cluster' }79+];80+81+var users = [82+ { name: 'tobi' }83+ , { name: 'loki' }84+ , { name: 'jane' }85+];86+87+var userRepos = {88+ tobi: [repos[0], repos[1]]89+ , loki: [repos[1]]90+ , jane: [repos[2]]91+};92+93+// we now can assume the api key is valid,94+// and simply expose the data95+96+app.get('/api/users', function(req, res, next){97+ res.send(users);98+});99+100+app.get('/api/repos', function(req, res, next){101+ res.send(repos);102+});103+104+app.get('/api/user/:name/repos', function(req, res, next){105+ var name = req.params.name106+ , user = userRepos[name];107+ 108+ if (user) res.send(user);109+ else next();110+});111+112+if (!module.parent) {113+ app.listen(3000);114+ console.log('Express server listening on port 3000');115+}added:test/acceptance/web-service.js+48 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
var request = require('../support/http') , 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){ request(app) .get('/api/users') .expect(400, done); }) })
describe('with an invalid api key', function(){ it('should respond with 401 unauthorized', function(done){ request(app) .get('/api/users?api-key=rawr') .expect(401, done); }) })
describe('with a valid api key', function(){ it('should respond users json', function(done){ request(app) .get('/api/users?api-key=foo') .end(function(res){ res.should.be.json; res.body.should.equal('[{"name":"tobi"},{"name":"loki"},{"name":"jane"}]'); done(); }); }) }) })
describe('when requesting an invalid route', function(){ it('should respond with 404 json', function(done){ request(app) .get('/api/something?api-key=bar') .end(function(res){ res.should.have.status(404); res.should.be.json; res.body.should.equal('{"error":"Lame, can\'t find that"}'); done(); }); }) })})No newline at end of file