Skip to content

Commit

Permalink
🎨 Improve batch guard to privent race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
WeiJun0827 authored and williamchong committed Oct 11, 2022
1 parent be1dfb7 commit afb1f6b
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/util/api/likernft/user.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
import { db } from '../../firebase';
import { getNFTISCNOwner } from '../../cosmos/nft';

const BATCH_SIZE = 200;

export async function filterOwnedClassIds(iscnDocs, wallet) {
const classIdSet = new Set();
iscnDocs.forEach((doc) => {
classIdSet.add(doc.data().classId);
});
let count = 0;
let batch = db.batch();
const promises = iscnDocs.map(async (doc) => {
const docsToUpdate = [];
const checkOwnerPromises = iscnDocs.map(async (doc) => {
const iscnPrefix = decodeURIComponent(doc.id);
const owner = await getNFTISCNOwner(iscnPrefix);
if (owner && owner !== wallet) {
docsToUpdate.push(doc);
classIdSet.delete(doc.data().classId);
batch.update({ ownerWallet: owner });
count += 1;
if (count % 200 === 0) {
await batch.commit();
batch = db.batch();
}
}
});
await Promise.all(promises);
if (count % 200) await batch.commit();
await Promise.all(checkOwnerPromises);

if (docsToUpdate.length) {
const batches = [];
for (let i = 0; i < docsToUpdate.length; i += BATCH_SIZE) {
batches.push(docsToUpdate.slice(i, i + BATCH_SIZE));
}
const updatePromises = batches.map((docs) => {
const batch = db.batch();
docs.forEach(doc => batch.update(doc.ref, { ownerWallet: wallet }));
return batch.commit();
});
await Promise.all(updatePromises);
}
return Array.from(classIdSet);
}

Expand Down

0 comments on commit afb1f6b

Please sign in to comment.