Skip to content

Commit

Permalink
route methods added fro checking request method
Browse files Browse the repository at this point in the history
  • Loading branch information
krutoo committed Mar 5, 2024
1 parent d03b38f commit ccd51e5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 19 deletions.
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,17 @@ import { router, route } from '@krutoo/fetch-tools';
Bun.serve({
port: 1234,
fetch: router(
route('/', () => new Response('Home page')),
route('/news', () => new Response('News page')),
route('/about', () => new Response('About page')),
// handler of GET /
route.get('/', () => new Response('Home page')),

// handler of PUT /about
route.put('/about', () => new Response('About page')),

// handler of POST /news
route.post('/news', () => new Response('News page')),

// handler for any method
route('/stats', () => new Response('Some stats')),
),
});
```
Expand Down
40 changes: 24 additions & 16 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ interface Route {
handler: Handler;
}

type RoutePattern = string | ((url: URL, request: Request) => boolean);

export function router(...routes: Route[]): Handler {
return request => {
const url = new URL(request.url);
Expand All @@ -19,10 +21,7 @@ export function router(...routes: Route[]): Handler {
};
}

export function route(
pattern: string | ((url: URL, request: Request) => boolean),
handler: Handler,
): Route {
export function route(pattern: RoutePattern, handler: Handler): Route {
if (typeof pattern === 'function') {
return {
is: pattern,
Expand All @@ -36,19 +35,28 @@ export function route(
};
}

route.get = (
pattern: string | ((url: URL, request: Request) => boolean),
handler: Handler,
): Route => {
if (typeof pattern === 'function') {
route.get = createRouteFactoryForMethod('get');
route.post = createRouteFactoryForMethod('post');
route.put = createRouteFactoryForMethod('put');
route.delete = createRouteFactoryForMethod('delete');
route.head = createRouteFactoryForMethod('head');
route.options = createRouteFactoryForMethod('options');
route.connect = createRouteFactoryForMethod('connect');

function createRouteFactoryForMethod(method: string) {
const isSuitableMethod = (request: Request) => request.method.toLowerCase() === method;

return (pattern: RoutePattern, handler: Handler): Route => {
if (typeof pattern === 'function') {
return {
is: (url, req) => isSuitableMethod(req) && pattern(url, req),
handler,
};
}

return {
is: pattern,
is: (url, request) => isSuitableMethod(request) && url.pathname === pattern,
handler,
};
}

return {
is: (url, request) => request.method.toLowerCase() === 'get' && url.pathname === pattern,
handler,
};
};
}

0 comments on commit ccd51e5

Please sign in to comment.