garybernhardt/static-path

Using patterns in nested express routers

Opened this issue · 1 comments

I'm currently working on and express backend with isolated routers.

Example

app.ts

const app = express()
app.use('/api', api)
app.get('/', (req, res) => res.send('hello world'))
app.use(catch404)
app.use(errorHandler)

api.ts

const api = router()
api.use(authValidation)
api.get('/some/random/endpoint', (req, res) => res.json({ hello: 'world' }))
api.use(apiCatch404)
api.use(apiErrorHandler)

Problem

I would like to obviously include the whole path with this util, eg /api/some/random/endpoint. But doing so breaks the current pattern of using routers. As it either adds a redundant parts, or need additional engineering around using the whole patterns. Thank you

Alternatives I've thought of:

  • The bad alternative I'm currently using is to omit the /api from the pattern then adding any prefixes one the requests.
  • I'm thinking of nesting routers and using the whole pattern, but including the wrapping handlers per endpoint. This misses the 404 handler though and means every request is at least checked against every handler before it
  • Using two paths per endpoint, one for the server, one for the client. But this entirely defeats the point of this util

Ideal

My ideal would be to have some sort of interface that allows me to programmatically omit segments off the start inside the endpoint. For instance:

const apiPath = staticPath('/api/some/random/endpoint')
apiPath.omit('/api') // /some/random/endpoint
apiPath.omit('/api/some') // /random/endpoint

This wouldn't be ideal in the scheme of things, but IMO this would be the better of a bad world

PS

I fear this is a won't fix due to technical difficulties. But would at least appreciate some input if available.

have you checked my workaround to the similar problem of angular nested routing in #4 (comment)?

TLDR:
remove the parent prefix from the path api.get(cleanRoutePattern(paths.x_api_some_random_endpoint.pattern, paths.x_api.pattern)) so both parent and child have a proper static path.

with

function cleanRoutePattern(route: string, prefixToRemove = '') {
  return route.replace(prefixToRemove + '/', '');
}