Files
WhatIDo/lib/photo-cleanup.js
T

61 lines
1.7 KiB
JavaScript

'use strict';
const FACE_REF_TABLES = ['student_face_refs', 'photo_faces'];
function isFaceTable(table) {
return FACE_REF_TABLES.includes(table);
}
async function findBrokenFaceRefs(pool, storage, { studentId, limit } = {}) {
const results = [];
for (const table of FACE_REF_TABLES) {
let sql;
const params = [];
if (table === 'student_face_refs') {
sql = `SELECT id, photo_path, student_id FROM student_face_refs WHERE photo_path IS NOT NULL AND photo_path <> ''`;
if (studentId) {
sql += ` AND student_id = $${params.length + 1}`;
params.push(studentId);
}
} else {
sql = `SELECT id, photo_path, student_id FROM photo_faces WHERE photo_path IS NOT NULL AND photo_path <> ''`;
if (studentId) {
sql += ` AND student_id = $${params.length + 1}`;
params.push(studentId);
}
}
sql += ` ORDER BY id`;
if (limit) {
sql += ` LIMIT $${params.length + 1}`;
params.push(limit);
}
const { rows } = await pool.query(sql, params);
for (const row of rows) {
const key = storage.keyFromPath(row.photo_path);
if (!key) continue;
const exists = await storage.exists(key);
if (!exists) {
results.push({ table, id: row.id, photo_path: row.photo_path, student_id: row.student_id });
}
}
}
return results;
}
async function deleteFaceRef(pool, storage, { table, id }) {
if (!isFaceTable(table)) {
throw new Error('Недопустимая таблица');
}
const { rows } = await pool.query(
`DELETE FROM ${table} WHERE id = $1 RETURNING id, photo_path`,
[id]
);
return rows[0] || null;
}
module.exports = {
findBrokenFaceRefs,
deleteFaceRef,
FACE_REF_TABLES,
};