import type Router from "@koa/router"; import type { default as Koa } from "koa"; import mount from "koa-mount"; import Static from "koa-static"; import { Middlewares } from "sealious"; import type TheApp from "../app.js"; import { imageRouter, RESPONSIVE_IMAGES_URL_PATH } from "../image-router.js"; import { customUrlView } from "./middlewares/customUrlView.js"; import mountAutoRoutes from "./routes.js"; import _locreq from "locreq"; import sitemapPage from "../sitemap.xml.js"; const locreq = _locreq(new URL("./", import.meta.url).pathname); export const mainRouter = (app: TheApp, koa_app: Koa, router: Router): void => { const started_at = Date.now(); // necessary to detect aplication restarts router.get("(.*)", async (ctx, next) => { // custom redirects if (ctx.body) return; const { items: [redirect], } = await app.collections.redirects .suList() .filter({ from_url: ctx.url }) .fetch(); if (redirect) { ctx.status = parseInt(redirect.get("type")); ctx.redirect(redirect.get("to_url")); return; } await next(); }); koa_app.use(mount("/", Static(locreq.resolve("public")))); koa_app.use(Middlewares.extractContext()); koa_app.use(customUrlView(app)); app.initRouter(router); koa_app.use(router.routes()); router.use(Middlewares.extractContext()); router.get("/status.json", Middlewares.extractContext(), async (ctx) => { ctx.body = { status: ctx.$app.status, started_at }; }); router.get("/sitemap.xml", async (ctx) => { ctx.set("Content-Type", "application/xml"); ctx.body = await sitemapPage.render(ctx); }); router.use(RESPONSIVE_IMAGES_URL_PATH, imageRouter.getRoutes()); mountAutoRoutes(router); };