feat: add settings caching middleware for API routes

This commit is contained in:
Ricardo
2026-03-31 21:45:06 +02:00
parent 1797c4dbcf
commit d0dc5e599c
2 changed files with 40 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
/**
* Settings cache middleware for Mastodon API hot paths.
*
* Loads settings once per minute (not per request) and attaches
* to req.app.locals.apSettings for all downstream handlers.
*/
import { getSettings } from "../../settings.js";
let cachedSettings = null;
let cacheExpiry = 0;
const CACHE_TTL = 60_000; // 1 minute
export async function loadSettingsMiddleware(req, res, next) {
try {
const now = Date.now();
if (cachedSettings && now < cacheExpiry) {
req.app.locals.apSettings = cachedSettings;
return next();
}
const collections = req.app.locals.application?.collections;
cachedSettings = await getSettings(collections);
cacheExpiry = now + CACHE_TTL;
req.app.locals.apSettings = cachedSettings;
next();
} catch {
// On error, use defaults
if (!cachedSettings) {
const { DEFAULTS } = await import("../../settings.js");
cachedSettings = { ...DEFAULTS };
}
req.app.locals.apSettings = cachedSettings;
next();
}
}
+5
View File
@@ -8,6 +8,7 @@
import express from "express";
import rateLimit from "express-rate-limit";
import { corsMiddleware } from "./middleware/cors.js";
import { loadSettingsMiddleware } from "./middleware/load-settings.js";
import { tokenRequired, optionalToken } from "./middleware/token-required.js";
import { errorHandler, notImplementedHandler } from "./middleware/error-handler.js";
@@ -77,6 +78,10 @@ export function createMastodonRouter({ collections, pluginOptions = {} }) {
// ─── CORS ───────────────────────────────────────────────────────────────
router.use("/api", corsMiddleware);
router.use("/oauth/token", corsMiddleware);
// ─── Settings cache ────────────────────────────────────────────────────
// Loads plugin settings once per minute, available as req.app.locals.apSettings
router.use("/api", loadSettingsMiddleware);
router.use("/oauth/revoke", corsMiddleware);
router.use("/.well-known/oauth-authorization-server", corsMiddleware);