Skip to content

Instantly share code, notes, and snippets.

@kasuganosora
Created February 12, 2023 03:13
Show Gist options
  • Save kasuganosora/ca99f1a7d3fed847afcf5ee9f4c2df8d to your computer and use it in GitHub Desktop.
Save kasuganosora/ca99f1a7d3fed847afcf5ee9f4c2df8d to your computer and use it in GitHub Desktop.
cloudflare worker router
// Routes
const ROUTES = {
// 'GET /api/posts': 'getPosts',
// 'GET /api/posts/:id': 'getPost',
// 'GET /api/posts/:id/comments': 'getComments',
// 'GET /api/categories': 'getCategories',
// 'GET /api/tags': 'getTags',
// 'GET /api/configs': 'getConfigs',
// 'GET /api/admin/posts': 'getAdminPosts',
// 'POST /api/admin/posts': 'createPost',
// 'PUT /api/admin/posts/:id': 'updatePost',
// 'DELETE /api/admin/posts/:id': 'deletePost',
// 'GET /api/admin/categories': 'getAdminCategories',
// 'POST /api/admin/categories': 'createCategory',
// 'PUT /api/admin/categories/:id': 'updateCategory',
// 'DELETE /api/admin/categories/:id': 'deleteCategory',
// 'GET /api/admin/tags': 'getAdminTags',
// 'POST /api/admin/tags': 'createTag',
// 'PUT /api/admin/tags/:id': 'updateTag',
// 'DELETE /api/admin/tags/:id': 'deleteTag',
// 'GET /api/admin/configs': 'getAdminConfigs',
// 'POST /api/admin/configs': 'createConfig',
// 'PUT /api/admin/configs/:id': 'updateConfig',
// 'DELETE /api/admin/configs/:id': 'deleteConfig',
// 'GET /api/admin/comments': 'getAdminComments',
// 'POST /api/admin/comments': 'createComment',
// 'DELETE /api/admin/comments/:id': 'deleteComment',
'GET /api/hello': 'hello',
'GET /api/echo/:text/:text2': 'echo',
};
let handlers = {}
// handle routes
async function handleRoute(request) {
const { pathname, search } = new URL(request.url);
const method = request.method;
let response = null;
Object.keys(ROUTES).forEach((route) => {
let [routeMethod, routePath] = route.split(' ');
let routeRegex = new RegExp(`^${routePath.replace(/:\w+/g, '(\\w+)')}$`);
let routeMatch = pathname.match(routeRegex);
if (method === routeMethod && routeMatch) {
let handler = ROUTES[route];
let params = {};
let routeParts = routePath.split('/');
for (let i = 0; i < routeParts.length; i++) {
if (routeParts[i].startsWith(':')) {
console.log(i)
params[routeParts[i].slice(1)] = routeMatch[i-2];
}
}
request.query = getSearchParams(search);
response = handlers[handler](request, params);
return;
}
});
if (response) {
return response;
}
// Route not found
return new Response('Resource not found', { status: 404, 'Content-Type': 'text/plain' })
}
function getSearchParams(search) {
const searchParams = new URLSearchParams(search);
const map = new Map();
for (const [key, value] of searchParams) {
if (!map.has(key)) {
map.set(key, []);
}
map.get(key).push(value);
}
return map;
}
// handlers
handlers.hello = async (request, params) => {
return new Response('Hello World!', { status: 200, 'Content-Type': 'text/plain' })
};
handlers.echo = async (request, params) => {
return new Response(params.text + "-" + params.text2, { status: 200, 'Content-Type': 'text/plain' })
};
// main
export default {
async fetch(request, env) {
try {
request.env = env
return handleRoute(request)
} catch(e) {
return new Response(e.stack, { status: 500 })
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment