import _ from 'lodash'; import mongoose from 'mongoose'; import zlib from 'zlib'; import { nanoid } from 'nanoid'; import { model as HomebrewModel } from '../../homebrew.model.js'; import { getGitModels } from './git.js'; // BrewRepository (Mongo, ADR 0002): ruft exakt die Statics/Methoden auf, die der Upstream-Code // bisher direkt aufgerufen hat (HomebrewModel.get, getByUser, increaseView, findOne …). // Ergebnisse sind plain objects mit `id` (statt `_id`) und entpacktem `text` (kein `textBin`). const toPlain = (docOrObj)=>{ if(!docOrObj) return null; if(typeof docOrObj !== 'object') return docOrObj; const obj = docOrObj.toObject ? docOrObj.toObject() : { ...docOrObj }; const { _id, __v, textBin, ...rest } = obj; if(textBin && rest.text === undefined) rest.text = zlib.inflateRawSync(Buffer.isBuffer(textBin) ? textBin : (textBin.buffer ?? textBin)).toString(); return _id === undefined ? rest : { id: String(_id), ...rest }; }; const withoutId = (brew)=>_.omit(brew, ['id', '_id']); const RENDERER_QUERY = { legacy: { renderer: 'legacy' }, V3: { renderer: 'V3' } }; const searchQuery = ({ title, author, renderer })=>({ $and : [ { published: true }, RENDERER_QUERY[renderer] ?? {}, title ? { $text: { $search: title, $caseSensitive: false } } : {}, author ? { authors: author } : {} ] }); const SORT_FIELDS = ['title', 'createdAt', 'updatedAt', 'lastViewed', 'views', 'pageCount', 'version']; const lockProjection = { shareId: 1, editId: 1, title: 1, lock: 1 }; const mapIds = (docs)=>docs.map((doc)=>{ if(typeof doc !== 'object' || doc === null) return doc; const { _id, ...rest } = doc; return _id === undefined ? rest : { id: String(_id), ...rest }; }); const asProjection = (fields)=>fields && !Array.isArray(fields) ? Object.keys(fields).filter((k)=>fields[k]) : fields; // Kaskade (ADR 0003 §2): beim Löschen eines Brews fällt seine Git-Verknüpfung weg. // Ohne Verbindung (Unit-Specs mit gemocktem Modell) gibt es nichts zu löschen. const connected = ()=>mongoose.connection.readyState === 1; const removeGitLink = async (brewId)=>{ if(connected()) await getGitModels().Link.deleteOne({ brewId }); }; export const createBrewRepository = ()=>{ const find = async (query, fields)=>{ const doc = await (fields ? HomebrewModel.get(query, asProjection(fields)) : HomebrewModel.get(query)) .catch(()=>null); return toPlain(doc); }; return { async findByEditId(editId, { fields } = {}) { return find({ editId }, fields); }, async findByShareId(shareId, { fields } = {}) { return find({ shareId }, fields); }, async findByEditOrShareId(id) { return find({ $or: [{ editId: id }, { shareId: id }] }); }, async listByAuthor(username, { includeUnpublished = false, fields, tagsAny } = {}) { const filter = tagsAny ? { tags: { $in: tagsAny } } : null; const brews = fields ? await HomebrewModel.getByUser(username, includeUnpublished, fields, filter) : await HomebrewModel.getByUser(username, includeUnpublished, { text: 0, textBin: 0 }, filter); return brews.map(toPlain); }, async countByAuthor(username, { storage = 'homebrewery' } = {}) { const query = { authors: username, ...(storage === 'homebrewery' ? { googleId: { $exists: false } } : {}) }; return HomebrewModel.countDocuments(query); }, async existsAuthor(username) { return !!(await HomebrewModel.exists({ authors: username })); }, async create(brew) { const input = withoutId(brew); const doc = new HomebrewModel(input); doc.editId = input.editId ?? nanoid(12); doc.shareId = input.shareId ?? nanoid(12); // Explizit auf undefined gesetzte Felder (Stub-Brews: text) dürfen keine Schema-Defaults bekommen for (const key of Object.keys(input)) { if(input[key] === undefined) doc[key] = undefined; } const saved = await doc.save(); const plain = toPlain(saved); if(input.text !== undefined) plain.text = input.text; // nach save() steckt der Text in textBin return plain; }, async update(brew) { if(!brew.id) throw new Error('BrewRepository.update braucht eine id'); const doc = await HomebrewModel.findOne({ _id: brew.id }); if(!doc) return null; const merged = _.assign(doc, withoutId(brew)); if(brew.text !== undefined) merged.markModified('text'); // auch bei text === '' (Default) speichern const saved = await merged.save(); const plain = toPlain(saved); if(brew.text !== undefined) plain.text = brew.text; return plain; }, async deleteById(id) { const res = await HomebrewModel.deleteOne({ _id: id }); const deleted = (res?.deletedCount ?? 0) > 0; if(deleted) await removeGitLink(String(id)); return deleted; }, async deleteByEditId(editId) { const doc = connected() ? await HomebrewModel.findOne({ editId }, { _id: 1 }) : null; const res = await HomebrewModel.deleteOne({ editId }); const deleted = (res?.deletedCount ?? 0) > 0; if(deleted && doc) await removeGitLink(String(doc._id)); return deleted; }, async incrementViews(shareId) { return toPlain(await HomebrewModel.increaseView({ shareId })); }, async renameAuthor(oldName, newName) { const brews = await HomebrewModel.getByUser(oldName, true, ['authors']); await Promise.all(brews.map((brew)=>HomebrewModel.updateOne( { _id: brew._id }, { $set: { authors: brew.authors.map((a)=>a === oldName ? newName : a) } } ))); return brews.length; }, // { title, author, renderer: 'legacy'|'V3', sort, dir, skip, limit, withTotal } async searchPublished(params) { const { sort = 'title', dir = 'asc', skip = 0, limit = 20, withTotal = false } = params; const query = searchQuery(params); let brews = []; if(limit > 0) { const sortField = SORT_FIELDS.includes(sort) ? sort : 'title'; const docs = await HomebrewModel.find(query, { editId: 0, googleId: 0, text: 0, textBin: 0, version: 0 }) .sort({ [sortField]: dir === 'asc' ? 1 : -1 }) .skip(skip) .limit(limit) .maxTimeMS(5000) .exec(); brews = docs.map(toPlain); } const total = withTotal ? await HomebrewModel.countDocuments(query) : undefined; return { brews, total }; }, // --- Admin --- async countAll() { return HomebrewModel.countDocuments({}); }, async countPublished() { return HomebrewModel.countDocuments({ published: true }); }, async countLocked() { return HomebrewModel.countDocuments({ lock: { $exists: true } }); }, async listLocked() { return mapIds(await HomebrewModel.aggregate([{ $match: { lock: { $exists: 1 } } }, { $project: lockProjection }])); }, async listReviewRequests() { return mapIds(await HomebrewModel.aggregate([{ $match: { 'lock.reviewRequested': { $exists: 1 } } }, { $project: lockProjection }])); }, // Ergebnis: { result, brew }; result ∈ 'locked' | 'not-found' | 'already-locked' async setLock(shareId, lock, { overwrite = false } = {}) { const doc = await HomebrewModel.findOne({ shareId }); if(!doc) return { result: 'not-found' }; if(doc.lock && !overwrite) return { result: 'already-locked', brew: toPlain(doc) }; doc.lock = lock; doc.markModified('lock'); await doc.save(); return { result: 'locked', brew: toPlain(doc) }; }, // result ∈ 'unlocked' | 'not-found' | 'not-locked' async removeLock(shareId) { const doc = await HomebrewModel.findOne({ shareId }); if(!doc) return { result: 'not-found' }; if(!doc.lock) return { result: 'not-locked', brew: toPlain(doc) }; doc.lock = undefined; doc.markModified('lock'); await doc.save(); return { result: 'unlocked', brew: toPlain(doc) }; }, // result ∈ 'requested' | 'not-found' | 'already-requested' async requestReview(shareId) { const doc = await HomebrewModel.findOne({ shareId, lock: { $exists: 1 } }); if(!doc) return { result: 'not-found' }; if(doc.lock.reviewRequested) return { result: 'already-requested', brew: toPlain(doc) }; doc.lock.reviewRequested = new Date(); doc.markModified('lock'); await doc.save(); return { result: 'requested', brew: toPlain(doc) }; }, // result ∈ 'removed' | 'not-found' async removeReviewRequest(shareId) { const doc = await HomebrewModel.findOne({ shareId, 'lock.reviewRequested': { $exists: 1 } }); if(!doc) return { result: 'not-found' }; doc.lock.reviewRequested = undefined; doc.markModified('lock'); await doc.save(); return { result: 'removed', brew: toPlain(doc) }; } }; };