This repository has been archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
search.js
64 lines (59 loc) · 1.63 KB
/
search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const MiniSearch = require('minisearch').default
const { and, descending, paginate, type, isPublic, toPullStream } = SSB.dbOperators
const pull = require('pull-stream')
const localPrefs = require('./localprefs')
var mostRecentMessage = null
function indexNewPosts(cb) {
pull(
SSB.db.query(
and(type('post'), isPublic()),
descending(),
paginate(SSB.search.depth),
toPullStream()
),
pull.take(1),
pull.drain((msgs) => {
for (m in msgs) {
if (msgs[m].key == mostRecentMessage)
break
if (msgs[m].value && msgs[m].value.content && msgs[m].value.content.text)
SSB.search.miniSearch.add({ key: msgs[m].key, text: msgs[m].value.content.text })
}
if (msgs && msgs.length > 0)
mostRecentMessage = msgs[0].key
cb()
})
)
}
if (!SSB.search) {
SSB.search = {
depth: localPrefs.getSearchDepth(),
miniSearch: new MiniSearch({
fields: ['text'],
idField: 'key'
}),
resetIndex: function() {
mostRecentMessage = null
},
fullTextSearch: function(searchTerm, cb) {
indexNewPosts(() => {
try {
var results = SSB.search.miniSearch.search(searchTerm, { fuzzy: 0.1 })
} catch(e) {
cb(e)
return
}
// Sometimes MiniSearch returns duplicates. Deduplicate them.
var seenKeys = []
var filteredResults = []
for (r in results) {
if (seenKeys.indexOf(results[r].id) < 0) {
filteredResults.push(results[r])
seenKeys.push(results[r].id)
}
}
cb(null, filteredResults)
})
}
}
}