23 lines
928 B
JavaScript
23 lines
928 B
JavaScript
'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});
|