Permalink
Browse files

added middleware handler

  • Loading branch information...
jgallen23 committed Sep 21, 2012
1 parent 12bf11f commit e30496ed2a0f780235bd1e4afcf25c97bea0e868
Showing with 39 additions and 31 deletions.
  1. 0 bin/fakejax.js
  2. 0 bin/fakeson.js
  3. +3 −31 lib/fakejax.js
  4. +36 −0 lib/handler.js
View
0 bin/fakejax.js 100644 → 100755
No changes.
View
0 bin/fakeson.js 100644 → 100755
No changes.
View
@@ -1,40 +1,12 @@
var http = require('http');
-var path = require('path');
-var fakeson = require('./fakeson');
+var handler = require('./handler');
-var cache = {};
var fakejax = function(folder, port, update) {
port = port || 8000;
- http.createServer(function (req, res) {
+ var handle = handler(folder, update);
- var url = req.url;
-
- var fullpath = path.join(folder, req.url+'.fakeson');
-
- try {
-
- var jsonString;
- if (!update && cache[fullpath]) {
- jsonString = cache[fullpath];
- } else {
- jsonString = fakeson(fullpath);
- cache[fullpath] = jsonString;
- }
-
- res.writeHead(200, {
- 'Content-Type': 'application/json',
- 'Access-Control-Allow-Origin': '*'
- });
-
- res.end(jsonString);
-
- } catch(e) {
- res.writeHead(500);
- res.end(e.message);
- }
-
- }).listen(port);
+ http.createServer(handle).listen(port);
console.log('Server running at http://127.0.0.1:'+port+'/');
}
View
@@ -0,0 +1,36 @@
+var path = require('path');
+var fakeson = require('./fakeson');
+
+
+module.exports = function(folder, update) {
+
+ var cache = {};
+
+ return function(req, res) {
+ var url = req.url;
+
+ var fullpath = path.join(folder, req.url+'.fakeson');
+
+ try {
+
+ var jsonString;
+ if (!update && cache[fullpath]) {
+ jsonString = cache[fullpath];
+ } else {
+ jsonString = fakeson(fullpath);
+ cache[fullpath] = jsonString;
+ }
+
+ res.writeHead(200, {
+ 'Content-Type': 'application/json',
+ 'Access-Control-Allow-Origin': '*'
+ });
+
+ res.end(jsonString);
+
+ } catch(e) {
+ res.writeHead(500);
+ res.end(e.message);
+ }
+ }
+}

0 comments on commit e30496e

Please sign in to comment.