Files
homebrewery-oidc/server/fork/cleanup/index.js
T
dev-bot BotandClaude Sonnet 5.5 ebcd324980
CI / Storage (postgres) (pull_request) Canceled after 0s
CI / App (npm ci + Build, ESLint, Stylelint, Jest) (pull_request) Canceled after 0s
CI / Storage (mongo) (pull_request) Canceled after 0s
fix(mongo): Admin-Cleanup räumt verwaiste Git-Links und Bild-Assets auf (#27)
POST /admin/cleanupJunk und /admin/cleanupLost löschen unter MongoDB per
deleteMany; brewgitlinks und brewassets blieben als Waisen zurück. Ein
Fork-Hook (server/fork/cleanup) läuft nach erfolgreichem Cleanup und entfernt
Links und Assets ohne Brew. server/admin.api.js bleibt unverändert.

Closes #27

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 01:48:17 +00:00

57 lines
2.6 KiB
JavaScript

import mongoose from 'mongoose';
import { model as HomebrewModel } from '../../homebrew.model.js';
// Admin-Cleanup unter MongoDB (Gitea #27): `POST /admin/cleanupJunk` und `/admin/cleanupLost` löschen Brews per
// `deleteMany` (Upstream, unverändert). Anders als unter Postgres (FK-Kaskade) bleiben dabei Git-Links
// (`brewgitlinks`) und Bild-Assets (`brewassets`) ohne Brew zurück. Dieser Hook räumt sie danach auf.
const COLLECTIONS = ['brewgitlinks', 'brewassets'];
const CLEANUP_ROUTE = /^\/admin\/cleanup(Junk|Lost)\/?$/;
const toObjectId = (id)=>mongoose.isValidObjectId(id) && String(new mongoose.Types.ObjectId(id)) === String(id).toLowerCase()
? new mongoose.Types.ObjectId(id) : null;
/**
* Entfernt Git-Links und Assets, deren Brew nicht mehr existiert.
* @returns {Promise<{ gitLinks: number, assets: number }>}
*/
export const cleanupOrphans = async (connection = mongoose.connection)=>{
const counts = {};
for (const name of COLLECTIONS) {
const coll = connection.collection(name);
const brewIds = (await coll.distinct('brewId')).map(String);
const asObjectId = new Map(brewIds.map((id)=>[id, toObjectId(id)]));
const valid = [...asObjectId.values()].filter(Boolean);
const existing = valid.length
? new Set((await HomebrewModel.find({ _id: { $in: valid } }, { _id: 1 }).lean()).map((d)=>String(d._id)))
: new Set();
const orphans = brewIds.filter((id)=>!existing.has(String(asObjectId.get(id))));
counts[name] = orphans.length ? (await coll.deleteMany({ brewId: { $in: orphans } })).deletedCount : 0;
}
return { gitLinks: counts.brewgitlinks, assets: counts.brewassets };
};
/**
* Express-Middleware vor `adminApi`: Nach einem erfolgreichen POST auf die Cleanup-Routen (HTTP 200, also Admin-Auth
* und Mongo-Prüfung bestanden) wird `cleanupOrphans` ausgeführt, bevor die Antwort rausgeht. Unter Postgres wirkungslos.
*/
export const createAdminCleanupHook = ({ getStorage, cleanup = cleanupOrphans, logger = console })=>(req, res, next)=>{
if(req.method !== 'POST' || !CLEANUP_ROUTE.test(req.path)) return next();
const send = res.json.bind(res);
res.json = async (body)=>{
res.json = send;
if(res.statusCode === 200 && getStorage().driver === 'mongo') {
try {
const orphans = await cleanup();
logger.info?.(`Admin-Cleanup: verwaiste Git-Links (${orphans.gitLinks}) und Assets (${orphans.assets}) entfernt.`);
} catch (err) {
logger.error?.('Admin-Cleanup: Aufräumen verwaister Git-Links/Assets fehlgeschlagen', err);
}
}
return send(body);
};
return next();
};
export default { cleanupOrphans, createAdminCleanupHook };