Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

regex-router

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

regex-router - npm Package Compare versions

Comparing version 0.2.0 to 1.0.0

index.ts

79

index.js

@@ -1,33 +0,52 @@

'use strict'; /*jslint es5: true, node: true, indent: 2 */
var Router = module.exports = function(default_func) {
this.nroutes = 0;
this.routes = [];
this.default = default_func || function() {};
var notFound = function (req, res) {
res.statusCode = 404;
res.end('Not Found\n');
};
Router.prototype.route = function(req, res) {
var m;
for (var i = 0; i < this.nroutes; i++) {
var route = this.routes[i];
var method_match = route.method == 'any' || route.method == req.method.toLowerCase();
if (method_match && (route.regex ? (m = req.url.match(route.regex)) : (m = req.url) === route.string)) {
return route.func(req, res, m);
var Router = (function () {
function Router(defaultHandler, routes) {
if (defaultHandler === void 0) { defaultHandler = notFound; }
if (routes === void 0) { routes = []; }
this.defaultHandler = defaultHandler;
this.routes = routes;
}
}
return this.default(req, res, req.url);
};
Router.prototype.add = function(method, url, func) {
/** add: append handler for given HTTP method and url to routes
`url`: String | RegExp
`func`: function(http.IncomingMessage, http.ServerResponse, String | RegExpMatch) */
var route = {method: method, func: func};
if (url instanceof RegExp) route.regex = url;
else route.string = url;
this.routes.push(route);
this.nroutes++;
};
['any', 'options', 'get', 'head', 'post', 'put', 'delete', 'trace', 'connect', 'patch'].forEach(function(method) {
// add router.get(url, func), router.GET(url, func) shortcuts for common http methods
Router.prototype[method] = Router.prototype[method.toUpperCase()] =
function(url, func) { this.add(method, url, func); };
/**
Iterate through all the routes, in order, calling the handler of the first
one that matches the incoming request.
*/
Router.prototype.route = function (req, res) {
for (var i = 0, route; (route = this.routes[i]); i++) {
// http.IncomingMessage#method is always uppercase for successful requests
// and the corresponding Route#method value should always be uppercase too
if (route.method == 'ANY' || route.method == req.method) {
var match = req.url.match(route.regExp);
if (match) {
return route.handler(req, res, match);
}
}
}
return this.defaultHandler(req, res);
};
/**
Append handler for given HTTP method and url to routes.
Use method = 'ANY'
*/
Router.prototype.add = function (method, regExp, handler) {
this.routes.push({ method: method.toUpperCase(), regExp: regExp, handler: handler });
};
/** Copied from http.METHODS, with special match-all ANY */
Router.HTTP_METHODS = ['ANY',
'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LOCK', 'M-SEARCH',
'MERGE', 'MKACTIVITY', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH', 'POST',
'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REPORT', 'SEARCH', 'SUBSCRIBE',
'TRACE', 'UNLOCK', 'UNSUBSCRIBE'];
return Router;
})();
/**
Add router.get(regExp, handler), router.GET(regExp, handler) shortcuts for
all official HTTP method names.
*/
Router.HTTP_METHODS.forEach(function (method) {
Router.prototype[method] = Router.prototype[method.toLowerCase()] =
function (url, func) { this.add(method, url, func); };
});
module.exports = Router;
{
"name": "regex-router",
"version": "0.2.0",
"version": "1.0.0",
"description": "Route http(s) requests via regular expressions",

@@ -21,8 +21,9 @@ "keywords": [

"devDependencies": {
"tap": "*",
"request": "*"
"mocha": "*",
"request": "*",
"typescript": "*"
},
"scripts": {
"test": "tap test"
"test": "make test"
}
}

@@ -5,4 +5,2 @@ # Regex-router

Only [31 lines of code](index.js) (not counting tests)!
## Example

@@ -16,7 +14,7 @@

var R = new Router(function(req, res, m) {
res.end('404. URL not found:', req.url);
res.end('404. URL not found: ' + req.url);
});
R.get(/^\/page\/(\w+)/, function(req, res, m) {
console.log('Serving URL:', req.url);
console.log('Serving URL: %s', req.url);
var page_name = m[1];

@@ -32,3 +30,3 @@ var page_path = __dirname + '/static_pages/' + page_name + '.html';

R.route(req, res);
}).listen(80, 'localhost');
}).listen(80);
```

@@ -38,2 +36,2 @@

Copyright © 2012–2013 Christopher Brown. [MIT Licensed](LICENSE).
Copyright 2012-2015 Christopher Brown. [MIT Licensed](http://opensource.org/licenses/MIT).

@@ -1,38 +0,46 @@

'use strict'; /*jslint es5: true, node: true, indent: 2 */
var tap = require('tap');
/*globals describe, it, before, after */
var http = require('http');
var assert = require('assert');
var request = require('request');
var Router = require('..');
tap.test('basic server', function(t) {
t.plan(2);
// set up the routes
var R = new Router(function(req, res) {
res.end('404 :: URL not found.');
describe('basic server', function() {
var server;
before(function(callback) {
// set up the routes
var R = new Router();
R.get(/^\/page\/(\w+)/, function(req, res, m) {
res.end('Fetching page "' + m[1] + '"');
});
// set up the server
var hostname = '127.0.0.1';
server = http.createServer(function(req, res) {
R.route(req, res);
}).listen(0, hostname, function() { // port = 0 finds random free port
// server running, ready to run tests
var port = server.address().port;
request = request.defaults({baseUrl: 'http://' + hostname + ':' + port + '/'});
callback();
});
});
R.get(/^\/page\/(\w+)/, function(req, res, m) {
res.end('Fetching page "' + m[1] + '"');
after(function() {
server.close();
});
// set up the server
var hostname = '127.0.0.1';
var server = require('http').createServer(function(req, res) {
R.route(req, res);
}).listen(0, hostname, function() { // port = 0 finds random free port
// server running, ready to run tests
var port = server.address().port;
var addrport = 'http://' + hostname + ':' + port;
request.get(addrport + '/page/contact', function(err, res, body) {
t.equal(body, 'Fetching page "contact"', 'Need to fetch page by name.');
it('should fetch page by name', function(callback) {
request.get({uri: '/page/contact'}, function(err, res, body) {
if (err) return callback(err);
assert.equal(body, 'Fetching page "contact"');
callback();
});
});
request.get(addrport + '/reference', function(err, res, body) {
t.equal(body, '404 :: URL not found.', 'Need to return 404 page.');
it('should return default "not found" message', function(callback) {
request.get({uri: '/reference'}, function(err, res, body) {
if (err) return callback(err);
assert.equal(body, 'Not Found\n');
callback();
});
});
t.tearDown(function() {
server.close();
});
});

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc