Skip to content
Myr

app.js

This file

Path

examples/format/app.js

67 lines · 1.4 KiB · JavaScript

Last changed by

refactored format exampleTj Holowaychukbefore adoption540192f

History of this file

Take it

The walk stopped after 200 commits: lines older than e562adc point at it.

Settings docsTj Holowaychukbefore adoptione562adc

lines 1–12why, one step back
1
2/**3 * Module dependencies.4 */56var express = require('../../lib/express');78var app = express.createServer();910// Fake items1112var items = [

refactored format exampleTj Holowaychukbefore adoption540192f

lines 13–15why, one step back
13 { name: 'foo' }
14 , { name: 'bar' }15 , { name: 'baz' }

Settings docsTj Holowaychukbefore adoptione562adc

lines 16–20why, one step back
16];
1718// Routes1920app.get('/', function(req, res, next){

refactored format exampleTj Holowaychukbefore adoption540192f

lines 21–25why, one step back
21 res.writeHead(200, { 'Content-Type': 'text/html' });
22 res.write('<p>Visit /item/2</p>');23 res.write('<p>Visit /item/2.json</p>');24 res.write('<p>Visit /item/2.xml</p>');25 res.end();

Settings docsTj Holowaychukbefore adoptione562adc

lines 26–28why, one step back
26});
2728app.get('/item/:id.:format?', function(req, res, next){

refactored format exampleTj Holowaychukbefore adoption540192f

lines 29–53why, one step back
29 var id = req.params.id
30 , format = req.params.format31 , item = items[id];32 // Ensure item exists33 if (item) {34 // Serve the format35 switch (format) {36 case 'json':37 // Detects json38 res.send(item);39 break;40 case 'xml':41 // Set contentType as xml then sends42 // the string43 var xml = ''44 + '<items>'45 + '<item>' + item.name + '</item>'46 + '</items>';47 res.contentType('.xml');48 res.send(xml);49 break;50 case 'html':51 default:52 // By default send some hmtl53 res.send('<h1>' + item.name + '</h1>');

Settings docsTj Holowaychukbefore adoptione562adc

line 54why, one step back
54 }

refactored format exampleTj Holowaychukbefore adoption540192f

lines 55–59why, one step back
55 } else {
56 // We could simply pass route control and potentially 40457 // by calling next(), or pass an exception like below.58 next(new Error('Item ' + id + ' does not exist'));59 }

Settings docsTj Holowaychukbefore adoptione562adc

lines 60–67why, one step back
60});
6162// Middleware6364app.use(express.errorHandler({ showStack: true }));6566app.listen(3000);67console.log('Express app started on port 3000');