Skip to content

Commit

Permalink
Refactor URL routing in src/index.ts
Browse files Browse the repository at this point in the history
URL routing in src/index.ts has been updated to improve error handling and readability. This includes segregating the validation checks into more granular checks; differentiating 'server' routes first, and then 'room' routes, allowing for more specific error messages and status codes. This also incorporates a 404 status response for invalid server routes and improves logging for missing username headers. These changes should enhance user feedback and ease future development.
  • Loading branch information
Ancocodet committed Nov 23, 2023
1 parent 06656ad commit feb9539
Showing 1 changed file with 25 additions and 18 deletions.
43 changes: 25 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,36 @@ const server = Bun.serve<ClientData>({
const url = new URL(request.url)
let routes = url.pathname.split("/")
// Rooms will be available via /room/<room-uuid>
if ( routes[1].toLowerCase() === 'server' && routes[2].toLowerCase() === 'room') {
if(routes.length < 4) {
return new Response(JSON.stringify({message: "No roomId provided"}), {status: 400})
}
if (routes[1].toLowerCase() === 'server') {

let roomId = routes[3].toLowerCase();
if(!roomId.match(/[a-z\d-]{6,}/)) {
return new Response(JSON.stringify({message: "Invalid roomId provided"}), {status: 400})
if (routes.length < 3) {
return new Response(JSON.stringify({message: 'Page not found'}), {status: 404});
}

// Check if a username is provided
if(!request.headers.has('X-Username')) {
logger.warning("Request with missing header was sent")
return new Response(JSON.stringify({message: "Username is required"}), {status: 400})
}
if (routes[2].toLowerCase() === 'room') {
if (routes.length < 4) {
return new Response(JSON.stringify({message: "No roomId provided"}), {status: 400})
}

const success = server.upgrade(request, {
data: {
roomId: roomId,
username: request.headers.get('X-Username')
let roomId = routes[3].toLowerCase();
if (!roomId.match(/[a-z\d-]{6,}/)) {
return new Response(JSON.stringify({message: "Invalid roomId provided"}), {status: 400})
}
});
return success ? undefined : new Response(JSON.stringify({message: "WebSocket upgrade error"}), { status: 400 });

// Check if a username is provided
if (!request.headers.has('X-Username')) {
logger.warning("Request with missing header was sent")
return new Response(JSON.stringify({message: "Username is required"}), {status: 400})
}

const success = server.upgrade(request, {
data: {
roomId: roomId,
username: request.headers.get('X-Username')
}
});
return success ? undefined : new Response(JSON.stringify({message: "WebSocket upgrade error"}), {status: 400});
}
} else if(routes[1].toLowerCase() === 'health') {
return handleHealthEndpoints(routes)
}
Expand Down

0 comments on commit feb9539

Please sign in to comment.