Skip to content

Commit 9e8f190

Browse files
authored
fix: add pagination to loadSpaces (#1042)
* fix: add pagination to loadSpaces * run map at the end * fix empty line * remove try catch like before
1 parent bd2843e commit 9e8f190

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

src/helpers/spaces.ts

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import log from './log';
66
import db from './mysql';
77

88
const RUN_INTERVAL = 120e3;
9+
const BATCH_SIZE = 70000;
910
const TEST_STRATEGIES = [
1011
'ticket',
1112
'api',
@@ -160,17 +161,37 @@ function mapSpaces(spaces: Record<string, any>) {
160161

161162
async function loadSpaces() {
162163
const startTime = +Date.now();
164+
let offset = 0;
165+
let allResults: any[] = [];
166+
let hasMore = true;
167+
let batchCount = 0;
168+
169+
while (hasMore) {
170+
const query = `
171+
SELECT id, settings, flagged, verified, turbo, turbo_expiration, hibernated, follower_count, proposal_count, vote_count
172+
FROM spaces
173+
WHERE deleted = 0
174+
ORDER BY id ASC
175+
LIMIT ?, ?
176+
`;
177+
178+
const results = await db.queryAsync(query, [offset, BATCH_SIZE]);
179+
batchCount++;
180+
181+
allResults = allResults.concat(results);
182+
offset += BATCH_SIZE;
183+
184+
log.info(
185+
`[spaces] loaded batch ${batchCount}: ${results.length} spaces (total: ${allResults.length})`
186+
);
163187

164-
const query = `
165-
SELECT id, settings, flagged, verified, turbo, turbo_expiration, hibernated, follower_count, proposal_count, vote_count
166-
FROM spaces
167-
WHERE deleted = 0
168-
ORDER BY id ASC
169-
`;
170-
const results = await db.queryAsync(query);
188+
if (results.length < BATCH_SIZE) {
189+
hasMore = false;
190+
}
191+
}
171192

172193
const spaces = Object.fromEntries(
173-
results.map(space => [
194+
allResults.map(space => [
174195
space.id,
175196
{
176197
...JSON.parse(space.settings),
@@ -188,7 +209,9 @@ async function loadSpaces() {
188209
);
189210

190211
log.info(
191-
`[spaces] total spaces ${Object.keys(spaces).length}, in (${(
212+
`[spaces] total spaces ${
213+
Object.keys(spaces).length
214+
}, in ${batchCount} batches (${(
192215
(+Date.now() - startTime) /
193216
1000
194217
).toFixed()}s)`

0 commit comments

Comments
 (0)