Permalink
Browse files

first commit

  • Loading branch information...
1 parent 1d25243 commit 7ba3b0298b4978ebef67aeb47dff1b511e1bc0ad @pgte committed Aug 31, 2012
Showing with 117 additions and 0 deletions.
  1. +22 −0 README.md
  2. +48 −0 index.js
  3. +17 −0 package.json
  4. +30 −0 test/index.js
View
@@ -0,0 +1,22 @@
+# Flatware::Cookie-Parser
+
+Cookie Parser middleware for Flatiron.js
+
+## Include as dependency
+
+Add "flatware-cookie-parser" to your dependencies in `package.json`.
+
+ $ npm install
+
+## Add it to the server
+
+```javascript
+var CookieParser = require('flatware-cookie-parser');
+
+ var server = union.createServer({
+ before: [
+ CookieParser(),
+ // ...
+ ]
+ });
+```
View
@@ -0,0 +1,48 @@
+function parseCookie(str){
+ var obj = {}
+ , pairs = str.split(/[;,] */);
+
+ for (var i = 0, len = pairs.length; i < len; ++i) {
+ var pair = pairs[i]
+ , eqlIndex = pair.indexOf('=')
+ , key = pair.substr(0, eqlIndex).trim()
+ , val = pair.substr(++eqlIndex, pair.length).trim()
+ ;
+
+ if ('"' == val[0]) val = val.slice(1, -1);
+
+ if (undefined == obj[key]) {
+ val = val.replace(/\+/g, ' ');
+ try {
+ obj[key] = decodeURIComponent(val);
+ } catch (err) {
+ if (err instanceof URIError) {
+ obj[key] = val;
+ } else {
+ throw err;
+ }
+ }
+ }
+ }
+ return obj;
+};
+
+function CookieParser(){
+ return function cookieParser(req, res) {
+ var cookie = req.headers.cookie;
+ if (req.cookies) return res.emit('next');
+
+ req.cookies = {};
+
+ if (cookie) {
+ try {
+ req.cookies = parseCookie(cookie);
+ } catch (err) {
+ return res.emit('error', err);
+ }
+ }
+ res.emit('next');
+ };
+};
+
+module.exports = CookieParser;
View
@@ -0,0 +1,17 @@
+{
+ "name": "flatware-cookie-parser",
+ "version": "0.1.0",
+ "author": {
+ "name": "Pedro Teixeira",
+ "email": "pedro.teixeira@gmail.com"
+ },
+ "devDependencies": {
+ "tap": "0.3.x"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ },
+ "scripts": {
+ "test": "node test"
+ }
+}
View
@@ -0,0 +1,30 @@
+var test = require('tap').test,
+ EE = require('events').EventEmitter;
+
+var cookieParser = require('..');
+
+test('should default to {} when no cookies are present', function(t) {
+ var req = {headers: {}},
+ res = new EE(),
+ parser = cookieParser()
+ ;
+
+ res.on('next', function() {
+ t.equivalent(req.cookies, {});
+ t.end();
+ });
+ parser(req, res);
+});
+
+test('should populate req.cookies', function(t) {
+ var req = {headers: {'cookie': 'abc=def; ghi=jkl'}},
+ res = new EE(),
+ parser = cookieParser()
+ ;
+
+ res.on('next', function() {
+ t.equivalent(req.cookies, {abc:'def', ghi:'jkl'});
+ t.end();
+ });
+ parser(req, res);
+});

0 comments on commit 7ba3b02

Please sign in to comment.