Change clear cache function to not load all assets into memory

This commit is contained in:
Mitchell McCaffrey 2021-06-28 08:25:54 +10:00
parent b7793626cf
commit 4bdf147e2b

View File

@ -184,25 +184,24 @@ let service = {
try { try {
let db = getDatabase({}); let db = getDatabase({});
const userId = (await db.table("user").get("userId")).value; const userId = (await db.table("user").get("userId")).value;
const cachedAssets = await db
const assetSizes = [];
await db
.table("assets") .table("assets")
.where("owner") .where("owner")
.notEqual(userId) .notEqual(userId)
.toArray(); .each((asset) => {
const totalSize = cachedAssets.reduce( assetSizes.push({ id: asset.id, size: asset.file.byteLength });
(acc, cur) => acc + cur.file.byteLength, });
0 const totalSize = assetSizes.reduce((acc, cur) => acc + cur.size, 0);
);
if (totalSize > maxCacheSize) { if (totalSize > maxCacheSize) {
// Remove largest assets first // Remove largest assets first
const largestAssets = cachedAssets.sort( const largestAssets = assetSizes.sort((a, b) => b.size - a.size);
(a, b) => b.file.byteLength - a.file.byteLength
);
let assetsToDelete = []; let assetsToDelete = [];
let deletedBytes = 0; let deletedBytes = 0;
for (let asset of largestAssets) { for (let asset of largestAssets) {
assetsToDelete.push(asset.id); assetsToDelete.push(asset.id);
deletedBytes += asset.file.byteLength; deletedBytes += asset.size;
if (totalSize - deletedBytes < maxCacheSize) { if (totalSize - deletedBytes < maxCacheSize) {
break; break;
} }