UNPKG

fets

Version:

TypeScript HTTP Framework focusing on e2e type-safety, easy setup, performance & great developer experience

65 lines (64 loc) 2.12 kB
const HTTP_METHODS = [ 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH', ]; export function useDefineRoutes() { return { onRoute({ basePath, route, routeByPathByMethod, routeByPatternByMethod, fetchAPI }) { let fullPath = ''; if (basePath === '/') { fullPath = route.path; } else if (route.path === '/') { fullPath = basePath; } else { fullPath = `${basePath}${route.path}`; } if (fullPath.includes(':') || fullPath.includes('*')) { const pattern = new fetchAPI.URLPattern({ pathname: fullPath }); function addHandler(method) { let methodPatternMaps = routeByPatternByMethod.get(method); if (!methodPatternMaps) { methodPatternMaps = new Map(); routeByPatternByMethod.set(method, methodPatternMaps); } methodPatternMaps.set(pattern, route); } if (!route.method) { for (const method of HTTP_METHODS) { addHandler(method); } } else { addHandler(route.method); } } else { function addHandler(method) { let methodPathMaps = routeByPathByMethod.get(method); if (!methodPathMaps) { methodPathMaps = new Map(); routeByPathByMethod.set(method, methodPathMaps); } methodPathMaps.set(fullPath, route); } if (!route.method) { for (const method of HTTP_METHODS) { addHandler(method); } } else { addHandler(route.method); } } }, }; }