dark icon indicating copy to clipboard operation
dark copied to clipboard

Utility function to detect whether a path matches a web-router route

Open Coachonko opened this issue 2 months ago • 7 comments

I need a function that would return me if a route is matched for a given path. Something like matchRoute(routesArray, path) which return null or an array of matched routes. This is because I need to be able to "filter" valid requests before hanging them to my Dark server script, otherwise Dark will render the application and return HTML when a non-existing file is requested. With a matchRoute function that returns null or an array where matchRouteArr[0].path === '**', I can immediately send an error 404, making my Dark server more efficient

import { join } from 'bun:path'

// tryFiles returns a static file from the build directory, if found. otherwise it passes the request
// to the specified handler.
export function tryFiles (elysiaContext, publicDir, handler) {
  const absolutePath = join(process.cwd(), publicDir, elysiaContext.path)

  // prevent relative path abuse
  const allowedBasePath = join(process.cwd(), publicDir, '/')
  if (!absolutePath.startsWith(allowedBasePath)) {
    return elysiaContext.error(403) // 'Forbidden'
  }

  if (absolutePath === allowedBasePath) {
    return handler(elysiaContext)
  }

  const file = Bun.file(absolutePath)
  // TODO if file is missing and not an application route, the handler (Dark) will return HTML. This is a problem.
  // Check application routes: if match give request to Dark, otherwise return elysiaContext.error(404) immediately
  if (file.size === 0) {
    return handler(elysiaContext)
  }

  return file
}

Update: I think there is a huge flaw in what I was attempting to do, and I will change my logic for sure. However, this function may still be useful to have.

Coachonko avatar Apr 19 '24 16:04 Coachonko