yufan.me/src/middleware.ts

31 lines
978 B
TypeScript
Raw Normal View History

2024-06-14 02:11:26 +08:00
import { posts } from '@/helpers/schema';
import { urlJoin } from '@/helpers/tools';
import { defineMiddleware } from 'astro:middleware';
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.
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();
});