Upload-Endpunkt POST /api/git/brews/:editId/assets (Magic Bytes, konfigurierbare Limits HB_ASSET_*, Dedupe, Commit ins Repo, Snapshot in brew_assets) und Auslieferung /git-assets/:shareId/:sha256.:ext gemäß ADR 0004. Postgres-Migration 0003, Mongo-Repo, Editor-Button, Drag-and-drop und Einfügen. Closes #10 Co-authored-by: Dev (Paperclip) <dev-bot@noreply.git.morlana.online>
77 lines
3.4 KiB
JavaScript
77 lines
3.4 KiB
JavaScript
import request from '../../homebrew/utils/request-middleware.js';
|
||
|
||
// Client-Seite des Bild-Uploads (ADR 0004 §5). Reine Funktionen und dünne API-Hülle, ohne React.
|
||
|
||
export const MIME_TYPE = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' };
|
||
|
||
const MIB = 1024 * 1024;
|
||
export const formatBytes = (n)=>{
|
||
if(n >= MIB) return `${+(n / MIB).toFixed(1)} MiB`;
|
||
if(n >= 1024) return `${Math.round(n / 1024)} KiB`;
|
||
return `${n} Byte`;
|
||
};
|
||
|
||
// Vorabprüfung mit den Limits des Servers, spart den Upload. Der Server prüft ohnehin erneut.
|
||
export const validateFile = (file, cfg)=>{
|
||
const type = MIME_TYPE[file.type];
|
||
if(!type || !cfg.types.includes(type))
|
||
return `„${file.name}“: Dieser Dateityp ist nicht erlaubt. Erlaubt sind: ${cfg.types.join(', ').toUpperCase()}.`;
|
||
if(file.size > cfg.maxBytes)
|
||
return `„${file.name}“ ist zu groß (${formatBytes(file.size)}). Erlaubt sind höchstens ${formatBytes(cfg.maxBytes)}.`;
|
||
if(file.size === 0) return `„${file.name}“ ist leer.`;
|
||
return null;
|
||
};
|
||
|
||
export const imageFiles = (fileList)=>Array.from(fileList ?? []).filter((f)=>f.type?.startsWith('image/'));
|
||
|
||
// Verständliche Meldung zu einem Fehler der API (A01–A07, G02–G05, G08, 412, 401)
|
||
export const describeError = (err)=>{
|
||
const code = err?.HBErrorCode;
|
||
const msg = err?.message;
|
||
if(err?.status === 412) return msg || 'Die Seite ist veraltet. Bitte neu laden.';
|
||
if(err?.status === 401) return 'Bitte melde dich an und prüfe, ob du Autor dieses Brews bist.';
|
||
if(code === 'G02') return 'Anmeldung am Git-Server fehlgeschlagen. Prüfe den Token der Verbindung (Schreibrecht nötig).';
|
||
if(code === 'G03') return 'Repository oder Branch nicht gefunden.';
|
||
if(code === 'G04') return 'Der Git-Server ist nicht erreichbar. Bitte später erneut versuchen.';
|
||
if(code === 'G05') return 'Speichern im Repository gerade nicht möglich. Bitte erneut versuchen.';
|
||
return msg || 'Das Bild konnte nicht hochgeladen werden.';
|
||
};
|
||
|
||
const unwrap = (promise)=>promise.then((res)=>res.body).catch((err)=>{
|
||
const body = err.response?.body ?? {};
|
||
const e = new Error(body.message || err.message);
|
||
e.status = err.response?.status;
|
||
e.HBErrorCode = body.HBErrorCode;
|
||
e.body = body;
|
||
throw e;
|
||
});
|
||
|
||
export const assetApi = {
|
||
config : ()=>unwrap(request.get('/api/git/assets/config')),
|
||
upload : (editId, file, { onProgress } = {})=>{
|
||
const req = request.post(`/api/git/brews/${editId}/assets`)
|
||
.set('Content-Type', file.type)
|
||
.set('X-HB-Filename', encodeURIComponent(file.name || 'image'))
|
||
.send(file);
|
||
if(onProgress) req.on('progress', (e)=>{ if(e.direction === 'upload' && e.percent != null) onProgress(Math.round(e.percent)); });
|
||
return unwrap(req);
|
||
}
|
||
};
|
||
|
||
// Dateien nacheinander hochladen. Liefert Markdown für alle erfolgreichen und die Fehlermeldungen.
|
||
export const uploadFiles = async (editId, files, cfg, { api = assetApi, onProgress } = {})=>{
|
||
const markdown = [];
|
||
const errors = [];
|
||
for (const [i, file] of files.entries()) {
|
||
const invalid = validateFile(file, cfg);
|
||
if(invalid) { errors.push(invalid); continue; }
|
||
try {
|
||
const res = await api.upload(editId, file, { onProgress: (p)=>onProgress?.({ index: i, total: files.length, percent: p, name: file.name }) });
|
||
markdown.push(res.markdown ?? `![${file.name.replace(/\.[^.]+$/, '')}](${res.url})`);
|
||
} catch (err) {
|
||
errors.push(`„${file.name}“: ${describeError(err)}`);
|
||
}
|
||
}
|
||
return { markdown, errors };
|
||
};
|