injectRoute.mjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * Used to inject an endpoint into our app that should only be available
  3. * when running in the test environment.
  4. *
  5. * @param app - a reference to the app.
  6. * @param searchFilter - a filter function to locate a route to position the new route immediatley after.
  7. * @param addRouteCallback - a callback that takes a router and creates the new route.
  8. */
  9. export function injectRouteAfter(app, searchFilter, addRouteCallback) {
  10. const stack = app._router.stack
  11. stack.forEach(layer => {
  12. if (layer.name !== 'router' || !layer.handle || !layer.handle.stack) {
  13. return
  14. }
  15. // Find the route that we want to position out new route after.
  16. const newRouteIndex = layer.handle.stack.findIndex(
  17. route => route && route.route && searchFilter(route.route)
  18. )
  19. if (newRouteIndex !== -1) {
  20. // Add our new endpoint to the end of the router stack.
  21. addRouteCallback(layer.handle)
  22. const routeStack = layer.handle.stack
  23. const sessionRoute = routeStack[routeStack.length - 1]
  24. // Then we reposition it next to the route we found previously.
  25. layer.handle.stack = [
  26. ...routeStack.slice(0, newRouteIndex),
  27. sessionRoute,
  28. ...routeStack.slice(newRouteIndex, routeStack.length - 1),
  29. ]
  30. }
  31. })
  32. }
  33. export default { injectRouteAfter }