2024-06-14 02:11:26 +08:00
|
|
|
import { posts } from '@/helpers/schema';
|
|
|
|
import { urlJoin } from '@/helpers/tools';
|
|
|
|
import { defineMiddleware } from 'astro:middleware';
|
|
|
|
|
2024-09-04 16:59:21 +08:00
|
|
|
const mappings = new Map<string, string>();
|
|
|
|
|
|
|
|
const rewrites = posts.map((post) => ({
|
|
|
|
sources: [
|
|
|
|
urlJoin('/', post.slug),
|
|
|
|
...post.alias.flatMap((alias) => [urlJoin('/', alias), urlJoin('/posts/', alias)]),
|
|
|
|
],
|
|
|
|
target: post.permalink,
|
|
|
|
}));
|
|
|
|
|
|
|
|
for (const rewrite of rewrites) {
|
|
|
|
for (const source of rewrite.sources) {
|
|
|
|
mappings.set(source, rewrite.target);
|
|
|
|
}
|
|
|
|
}
|
2024-06-14 02:11:26 +08:00
|
|
|
|
|
|
|
export const onRequest = defineMiddleware(({ request: { method }, url: { pathname }, redirect }, next) => {
|
|
|
|
// This is used for redirect my old blog posts to a new mapping.
|
2024-06-17 04:56:49 +08:00
|
|
|
const newTarget = mappings.get(pathname.endsWith('/') ? pathname.substring(0, pathname.length - 1) : pathname);
|
2024-06-14 02:11:26 +08:00
|
|
|
if (method === 'GET' && newTarget !== undefined) {
|
|
|
|
return redirect(newTarget, 301);
|
|
|
|
}
|
|
|
|
|
|
|
|
// return a Response or the result of calling `next()`
|
|
|
|
return next();
|
|
|
|
});
|