ddd
This commit is contained in:
parent
0a343ecbc5
commit
c3a6f5ff37
80 changed files with 2512 additions and 1625 deletions
23
server/http-router.js
Normal file
23
server/http-router.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
'use strict';
|
||||
|
||||
function routeKey(method,pathname){return `${String(method||'GET').toUpperCase()} ${pathname}`}
|
||||
|
||||
function createHttpRouter({notFound}={}){
|
||||
const routes=new Map();
|
||||
const add=(method,pathname,handler)=>{
|
||||
if(typeof handler!=='function')throw new TypeError('Route handler must be a function');
|
||||
const key=routeKey(method,pathname);
|
||||
if(routes.has(key))throw new Error(`Duplicate route: ${key}`);
|
||||
routes.set(key,handler);return api;
|
||||
};
|
||||
const dispatch=async(req,res,url)=>{
|
||||
const handler=routes.get(routeKey(req.method,url.pathname));
|
||||
if(handler)return handler(req,res,url);
|
||||
if(typeof notFound==='function')return notFound(req,res,url);
|
||||
return false;
|
||||
};
|
||||
const api=Object.freeze({add,dispatch,has:(method,pathname)=>routes.has(routeKey(method,pathname)),routes:()=>Object.freeze([...routes.keys()])});
|
||||
return api;
|
||||
}
|
||||
|
||||
module.exports=Object.freeze({routeKey,createHttpRouter});
|
||||
Loading…
Add table
Add a link
Reference in a new issue