Created
October 27, 2012 21:52
-
-
Save StevenMcD/3966512 to your computer and use it in GitHub Desktop.
NodeJS - Basic todo. More of a HTTP Verb handling exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
url = require('url'), | |
items = [], | |
server; | |
server = http.createServer(function(req, res){ | |
switch(req.method){ | |
case 'POST': | |
AddTodoItem(req, res, items); | |
break; | |
case 'GET': | |
GetAllItems(res, items); | |
break; | |
case 'DELETE': | |
EditItem(req, res, items, url, deleteItemFromArray); | |
break; | |
case 'PUT': | |
EditItem(req, res, items, url, updateItem); | |
break; | |
default: | |
//fail | |
break; | |
} | |
}).listen(3000); | |
function AddTodoItem(req, res, items){ | |
var item = ''; | |
req.setEncoding('utf8'); | |
req.on('data', function(chunk){ | |
item += chunk; | |
}); | |
req.on('end', function(){ | |
items.push(item); | |
res.end('OK\n'); | |
}); | |
}; | |
function GetAllItems(res, items){ | |
var body = items.map(function(item, i){ | |
return i + ') ' + item; | |
}).join('\n'); | |
res.setHeader('Content-Length', Buffer.byteLength(body)); | |
res.setHeader('Content-Type', 'text/plain; charset="utf-8"'); | |
res.end(body); | |
}; | |
function EditItem(req, res, items, url, callback){ | |
var path = url.parse(req.url).pathname, | |
i = parseInt(path.slice(1), 10); | |
if(isNaN(i)){ | |
res.statusCode = 400; | |
res.end('Invalid item id'); | |
} else if(!items[i]){ | |
res.statusCode = 404; | |
res.end('item id not found'); | |
} else { | |
callback(items, i, req); | |
res.end('OK\n'); | |
} | |
}; | |
function updateItem(items, indexToUpdate, req){ | |
var newToDo = url.parse(req.url).query; | |
req.setEncoding('utf8'); | |
items[indexToUpdate] = newToDo; | |
}; | |
function deleteItemFromArray(items, indexToRemove){ | |
items.splice(indexToRemove, 1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment