Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+92 added−0 removed
other:+92 added−0 removed
Provenance
Commit
fda31b7
Tree
34f3345
Author
Tj Holowaychuk <tj@vision-media.ca>
Committer
Tj Holowaychuk <tj@vision-media.ca>
Parent
8ca0a45
1 file changed+92 added−0 removed
added:examples/web-service/app.js+92 added
1+2+/**3+ * Module dependencies.4+ */5+6+var express = require('../../lib/express');7+8+var app = express.createServer();9+10+/**11+ * Generate our unique identifier.12+ */13+14+function uid() {15+ return [16+ Math.random() * 0xffff | 017+ , Math.random() * 0xffff | 018+ , Math.random() * 0xffff | 019+ , Date.now()20+ ].join('-');21+}22+23+// map of valid api keys, typically mapped to24+// account info with some sort of database like redis.25+// api keys do _not_ serve as authentication, merely to26+// track API usage or help prevent malicious behavior etc.27+28+var apiKeys = [uid(), uid(), uid()];29+30+console.log('valid keys:\n ', apiKeys.join('\n '));31+32+// these two objects will serve as our faux database33+34+var repos = [35+ { name: 'express', url: 'http://github.com/visionmedia/express' }36+ , { name: 'stylus', url: 'http://github.com/learnboost/stylus' }37+ , { name: 'cluster', url: 'http://github.com/learnboost/cluster' }38+];39+40+var users = [41+ { name: 'tobi' }42+ , { name: 'loki' }43+ , { name: 'jane' }44+];45+46+var userRepos = {47+ tobi: [repos[0], repos[1]]48+ , loki: [repos[1]]49+ , jane: [repos[2]]50+};51+52+// if we wanted to supply more than JSON, we could53+// use something similar to the content-negotiation54+// example.55+56+// here we validate the API key,57+// by mounting this middleware to /api/v158+// meaning only paths prefixed with "/api/v1"59+// will cause this middleware to be invoked60+61+app.use('/api/v1', function(req, res, next){62+ var key = req.query['api-key'];63+64+ // key isnt present65+ if (!key) return res.send('api key required', 401);66+67+ // key is invalid68+ if (!~apiKeys.indexOf(key)) return res.send('invalid api key', 401);69+70+ // all good, store req.key for route access71+ req.key = key;72+ next();73+});74+75+// we now can assume the api key is valid,76+// and simply expose the data77+78+app.get('/api/v1/users', function(req, res, next){79+ res.send(users);80+});81+82+app.get('/api/v1/repos', function(req, res, next){83+ res.send(repos);84+});85+86+app.get('/api/v1/user/:name/repos', function(req, res, next){87+ var name = req.params.name;88+ res.send(userRepos[name]);89+});90+91+app.listen(3000);92+console.log('Express server listening on port 3000');