Skip to content

Commit

Permalink
refactor: allow duplicates and always open new cursor for random note…
Browse files Browse the repository at this point in the history
…s fetch
  • Loading branch information
akhileshthite committed May 23, 2024
1 parent 4299062 commit b0acbb0
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions db.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,31 +227,24 @@ export class ActivityPubDB extends EventTarget {
await tx.done()
}

async * searchNotes ({ attributedTo } = {}, { skip = 0, limit = DEFAULT_LIMIT, sort = -1 } = {}) {
async * searchNotesRandom ({ limit = DEFAULT_LIMIT } = {}) {
const tx = this.db.transaction(NOTES_STORE, 'readonly')
let count = 0
const direction = sort > 0 ? 'next' : 'prev' // 'prev' for descending order
let cursor = null

const indexName = attributedTo ? ATTRIBUTED_TO_FIELD + ', published' : PUBLISHED_FIELD
const store = tx.objectStore(NOTES_STORE)
const totalNotes = await store.count()

const index = tx.store.index(indexName)
if (totalNotes === 0) return // Early exit if no notes are present

if (attributedTo) {
cursor = await index.openCursor([attributedTo], direction)
} else {
cursor = await index.openCursor(null, direction)
}
for (let i = 0; i < limit; i++) {
const randomSkip = Math.floor(Math.random() * totalNotes)
const cursor = await store.openCursor()

// Skip the required entries
if (skip) await cursor.advance(skip)
if (randomSkip > 0) {
await cursor.advance(randomSkip)
}

// Collect the required limit of entries
while (cursor) {
if (count >= limit) break
count++
yield cursor.value
cursor = await cursor.continue()
if (cursor) {
yield cursor.value
}
}

await tx.done
Expand Down

0 comments on commit b0acbb0

Please sign in to comment.