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

110 lines (84 loc) 3.4 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 Pattern = require('./pattern'); var Promise = require('bluebird'); var METHODS = ['get', 'post', 'put', 'del' , 'delete', 'head', 'options']; var HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'DELETE', 'HEAD', 'OPTIONS']; var routerAsync = function() { var methods = {}; var traps = {}; HTTP_METHODS.forEach(function(method) { methods[method] = []; }); var route = function limeroute(next) { var owin = this; var method = owin["owin.RequestMethod"]; var methodRoute = methods[method]; var trap = traps[method]; var url = owin["owin.RequestPath"]; var i = 0; if (!methodRoute) return next(); while (i < methodRoute.length) { var route = methodRoute[i]; i++; owin.Model = route.pattern(url); if (!owin.Model) continue; if (!owin["owin.RequestQueryString"]) parseQueryString(owin.Model, owin["owin.RequestQueryString"]); return route.fn.call(owin, function(){return Promise.resolve(null);}); } if (!trap) return next(); return trap.call(owin); }; METHODS.forEach(function(method, i) { route[method] = function routeInvoke(pattern, fn) { if (Array.isArray(pattern)) { pattern.forEach(function routeMethod(item) { route[method](item, fn); }); return; } if (!fn && !pattern) return route; if (!fn) return route[method](null, pattern); if (!pattern) { traps[HTTP_METHODS[i]] = fn; return route; } methods[HTTP_METHODS[i]].push({ pattern:Pattern(pattern), fn:fn }); return route; }; }); route.all = function routeAll(pattern, fn) { METHODS.forEach(function routeAllMethod(method) { route[method](pattern, fn); }); return route; }; return route; }; function parseQueryString(urlParams, query) { var match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }; while (match = search.exec(query)) urlParams[decode(match[1])] = decode(match[2]); } module.exports = routerAsync;