|
1 | | -import { defineMiddleware } from "astro/middleware"; |
| 1 | +import { sequence } from "astro/middleware"; |
| 2 | +import { latest_dir_name } from "../astro.config.mjs"; |
2 | 3 |
|
3 | | -export const onRequest = defineMiddleware((context, next) => { |
| 4 | +export const onRequest = sequence(redirectLatest, redirectSemver, redirectVersionRoot, redirectTutorialsRoot); |
4 | 5 |
|
5 | | - // path uses a semver (2.0.1) instead of a directory name (2_0) |
6 | | - let parts = context.url.pathname.match(/\/(?<major>[0-9]+)\.(?<minor>[0-9])+\.[0-9]+\/(?<rest>.*)$/); |
| 6 | +// redirect /latest to the latest version |
| 7 | +function redirectLatest(context, next) { |
| 8 | + if (context.url.pathname.slice(0, 7) == '/latest') { |
| 9 | + let rest = context.url.pathname.slice(context.url.pathname.length == 7 ? 7 : 8); |
| 10 | + return Response.redirect(new URL(`/${latest_dir_name}/${rest}`, context.url), 302); |
| 11 | + |
| 12 | + } |
| 13 | + |
| 14 | + return next(); |
| 15 | +} |
| 16 | + |
| 17 | +// redirect a semver (/2.0.1) to a directory name (/2_0) |
| 18 | +function redirectSemver(context, next) { |
| 19 | + let parts = context.url.pathname.match(/^\/(?<major>[0-9]+)\.(?<minor>[0-9])+\.[0-9]+(?<rest>\/.*)?$/); |
| 20 | + if (parts?.groups) { |
| 21 | + return Response.redirect(new URL(`/${parts.groups['major']}_${parts.groups['minor']}${parts.groups['rest'] || ''}`, context.url), 302); |
| 22 | + } |
| 23 | + |
| 24 | + return next(); |
| 25 | +} |
| 26 | + |
| 27 | +// redirect the version root (/2_0) to quickstart (/2_0/tutorials/quickstart) |
| 28 | +function redirectVersionRoot(context, next) { |
| 29 | + let parts = context.url.pathname.match(/^\/(?<major>[0-9]+)_(?<minor>[0-9])+\/?$/); |
| 30 | + if (parts?.groups) { |
| 31 | + return Response.redirect(new URL(`/${parts.groups['major']}_${parts.groups['minor']}/tutorials/quickstart`, context.url), 302); |
| 32 | + } |
| 33 | + |
| 34 | + return next(); |
| 35 | +}; |
| 36 | + |
| 37 | + |
| 38 | +// redirect the tutorials root (/2_0/tutorials) to quickstart (/2_0/tutorials/quickstart) |
| 39 | +function redirectTutorialsRoot(context, next) { |
| 40 | + let parts = context.url.pathname.match(/^\/(?<major>[0-9]+)_(?<minor>[0-9])+\/tutorials\/?$/); |
7 | 41 | if (parts?.groups) { |
8 | | - return Response.redirect(new URL(`/${parts.groups['major']}_${parts.groups['minor']}/${parts.groups['rest']}`, context.url), 301); |
| 42 | + return Response.redirect(new URL(`/${parts.groups['major']}_${parts.groups['minor']}/tutorials/quickstart`, context.url), 302); |
9 | 43 | } |
10 | 44 |
|
11 | 45 | return next(); |
12 | | -}); |
| 46 | +}; |
0 commit comments