Skip to content
Myr

Added simple web-service example

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 8ca0a45 · Browse files · 1 file+92 added−0 removed
This commit

State

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

1 file+92 added−0 removed

added:examples/web-service/app.js+92 added
12/**3 * Module dependencies.4 */56var express = require('../../lib/express');78var app = express.createServer();910/**11 * Generate our unique identifier.12 */1314function uid() {15 return [16 Math.random() * 0xffff | 017 , Math.random() * 0xffff | 018 , Math.random() * 0xffff | 019 , Date.now()20 ].join('-');21}2223// 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.2728var apiKeys = [uid(), uid(), uid()];2930console.log('valid keys:\n ', apiKeys.join('\n '));3132// these two objects will serve as our faux database3334var 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];3940var users = [41 { name: 'tobi' }42 , { name: 'loki' }43 , { name: 'jane' }44];4546var userRepos = {47 tobi: [repos[0], repos[1]]48 , loki: [repos[1]]49 , jane: [repos[2]]50};5152// if we wanted to supply more than JSON, we could53// use something similar to the content-negotiation54// example.5556// 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 invoked6061app.use('/api/v1', function(req, res, next){62 var key = req.query['api-key'];6364 // key isnt present65 if (!key) return res.send('api key required', 401);6667 // key is invalid68 if (!~apiKeys.indexOf(key)) return res.send('invalid api key', 401);6970 // all good, store req.key for route access71 req.key = key;72 next();73});7475// we now can assume the api key is valid,76// and simply expose the data7778app.get('/api/v1/users', function(req, res, next){79 res.send(users);80});8182app.get('/api/v1/repos', function(req, res, next){83 res.send(repos);84});8586app.get('/api/v1/user/:name/repos', function(req, res, next){87 var name = req.params.name;88 res.send(userRepos[name]);89});9091app.listen(3000);92console.log('Express server listening on port 3000');