UNPKG

lime-router

Version:

A lean and mean REST routing middleware for the limerun project (OWIN-JS reference implementation), for both HTTP and COAP servers

67 lines (54 loc) 1.81 kB
/* * Copyright 2015 Domabo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var decode = function(str) { try { return decodeURIComponent(str); } catch(err) { return str; } }; module.exports = function(pattern) { if (typeof pattern !== 'string') { // regex return function(url) { return url.match(pattern); }; } var keys = []; pattern = pattern.replace(/:(\w+)/g, '{$1}').replace('{*}', '*'); // normalize pattern = pattern.replace(/(\/)?(\.)?\{([^}]+)\}(?:\(([^)]*)\))?(\?)?/g, function(match, slash, dot, key, capture, opt, offset) { var incl = (pattern[match.length+offset] || '/') === '/'; keys.push(key); return (incl ? '(?:' : '')+(slash || '')+(incl ? '' : '(?:')+(dot || '')+'('+(capture || '[^/]+')+'))'+(opt || ''); }); pattern = pattern.replace(/([\/.])/g, '\\$1').replace(/\*/g, '(.+)'); pattern = new RegExp('^'+pattern+'[\\/]?$', 'i'); return function matchRoutePattern(str) { var match = str.match(pattern); if (!match) { return match; } var map = {}; match.slice(1).forEach(function(param, i) { var k = keys[i] = keys[i] || 'wildcard'; param = param && decode(param); map[k] = map[k] ? [].concat(map[k]).concat(param) : param; }); if (map.wildcard) { map['*'] = map.wildcard; } return map; }; };