|
| 1 | +const { |
| 2 | + getSortedRoutes: getSortedRoutesFromNext, |
| 3 | +} = require("next/dist/next-server/lib/router/utils/sorted-routes"); |
| 4 | + |
| 5 | +// Remove the file extension form the route |
| 6 | +const removeFileExtension = (route) => route.replace(/\.[a-zA-Z]+$/, ""); |
| 7 | + |
| 8 | +// Return an array of redirects sorted in order of specificity, i.e., more generic |
| 9 | +// routes precede more specific ones |
| 10 | +const getSortedRedirects = (redirects) => { |
| 11 | + // The @sls-next getSortedRoutes does not correctly sort routes with file |
| 12 | + // endings (e.g., json), so we remove them before sorting and add them back |
| 13 | + // after sorting |
| 14 | + const routesWithoutExtensions = redirects.map(({ route }) => |
| 15 | + removeFileExtension(route) |
| 16 | + ); |
| 17 | + |
| 18 | + // Sort the "naked" routes |
| 19 | + const sortedRoutes = getSortedRoutesFromNext(routesWithoutExtensions); |
| 20 | + |
| 21 | + // Return original routes in the sorted order |
| 22 | + return redirects.sort((a, b) => { |
| 23 | + // If routes are different, sort according to Next.js' getSortedRoutes |
| 24 | + if (a.route !== b.route) { |
| 25 | + return ( |
| 26 | + sortedRoutes.indexOf(removeFileExtension(a.route)) - |
| 27 | + sortedRoutes.indexOf(removeFileExtension(b.route)) |
| 28 | + ); |
| 29 | + } |
| 30 | + // Otherwise, put the route with more conditions first |
| 31 | + return (b.conditions || []).length - (a.conditions || []).length; |
| 32 | + }); |
| 33 | +}; |
| 34 | + |
| 35 | +module.exports = getSortedRedirects; |
0 commit comments