142
St
startsInvasion / files
startsInvasion / libs / node_modules / reqwest / build / dispatch / lib / dispatch.js
2.1 KB
1var url = require('url'); 2 3/* 4 * Accepts a nested set of object literals and creates a single-level object 5 * by combining the keys. 6 * 7 * flattenKeys({'a': {'b': function(){}, 'c': function(){}}}) 8 * {'ab': function(){}, 'ac': function(){}} 9 * 10 */ 11function flattenKeys(obj, /*optional args: */acc, prefix, prev_method){ 12 acc = acc || []; 13 prefix = prefix || ''; 14 Object.keys(obj).forEach(function(k){ 15 var split = splitURL(k); 16 if(typeof obj[k] == 'function') { 17 acc.push([prefix + split.url, split.method || prev_method, obj[k]]) 18 } 19 else { 20 flattenKeys(obj[k], acc, prefix + split.url, split.method); 21 } 22 }); 23 return acc; 24} 25 26/* 27 * Compiles the url patterns to a reqular expression, returning an array 28 * of arrays. 29 * 30 * compileKeys([['abc', 'GET', function(){}], ['xyz', 'POST', function(){}]]) 31 * [[/^abc$/, 'GET', function(){}], [/^xyz$/, 'POST', function(){}]] 32 */ 33function compileKeys(urls){ 34 return urls.map(function(url){ 35 // replace named params with regexp groups 36 var pattern = url[0].replace(/\/:\w+/g, '(?:/([^\/]+))'); 37 url[0] = new RegExp('^' + pattern + '$'); 38 return url; 39 }); 40} 41 42/* 43 * Break apart a url into the path matching regular expression and the 44 * optional method prefix. 45 */ 46function splitURL(url) { 47 var method, path, match = /^([A-Z]+)(?:\s+|$)/.exec(url); 48 if (match) { 49 method = match[1]; 50 path = /^[A-Z]+\s+(.*)$/.exec(url); 51 url = path ? path[1]: ''; 52 } 53 return {url: url, method: method}; 54} 55 56/* 57 * The exported function for use as a Connect provider. 58 * See test/test-dispatch.js for example usage. 59 */ 60module.exports = function(urls){ 61 var compiled = compileKeys(flattenKeys(urls)); 62 return function(req, res, next){ 63 if(!compiled.some(function(x){ 64 var match = x[0].exec(url.parse(req.url).pathname); 65 if (match) { 66 if (!x[1] || x[1] === req.method) { 67 x[2].apply(null, [req, res, next].concat(match.slice(1))); 68 return true; 69 } 70 } 71 return false; 72 })) next(); 73 }; 74};