-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathsearch.ts
89 lines (84 loc) · 2.17 KB
/
search.ts
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import randomWords from "random-words";
import { Doc } from "./_generated/dataModel";
import { mutation, query } from "./_generated/server";
import { CACHE_BREAKER_ARGS, rand, RAND_MAX } from "./common";
import { api } from "./_generated/api";
export const deleteMessageWithSearch = mutation({
args: {},
handler: async (ctx) => {
const toDelete = await ctx.runQuery(api.search.findRandomSearchDocument, {
cacheBreaker: Math.random(),
});
if (!toDelete) {
return;
}
await ctx.db.delete(toDelete._id);
},
});
export const replaceMessageWithSearch = mutation({
args: {},
handler: async (ctx) => {
const toReplace = await ctx.runQuery(api.search.findRandomSearchDocument, {
cacheBreaker: Math.random(),
});
if (!toReplace) {
return;
}
await ctx.db.replace(toReplace._id, {
channel: "global",
timestamp: toReplace.timestamp,
rand: rand(),
body: randomWords({ exactly: 1 }).join(" "),
ballastArray: [],
});
},
});
export default query({
handler: async (
{ db },
{
channel,
body,
limit,
}: {
channel: string;
body: string;
limit: number;
},
): Promise<Doc<"messages_with_search">[]> => {
return await db
.query("messages_with_search")
.withSearchIndex("search_body", (q) =>
q.search("body", body).eq("channel", channel),
)
.take(limit);
},
});
export const findRandomSearchDocument = query({
args: CACHE_BREAKER_ARGS,
handler: async ({ db }) => {
const lowestDoc = await db
.query("messages_with_search")
.withIndex("by_rand")
.order("asc")
.first();
if (!lowestDoc) {
return null;
}
const highestDoc = await db
.query("messages_with_search")
.withIndex("by_rand")
.order("desc")
.first();
if (!highestDoc) {
return null;
}
const percentage = rand() / RAND_MAX;
const range = highestDoc.rand - lowestDoc.rand;
const targetItemRand = percentage * range + lowestDoc.rand;
return await db
.query("messages_with_search")
.withIndex("by_rand", (q) => q.gte("rand", targetItemRand))
.first();
},
});