-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
220 lines (205 loc) · 5.8 KB
/
index.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import Mongoose from "mongoose";
declare module "mongoose" {
interface Aggregate<ResultType> {
/**
* Sort the current aggregation by `__seed` and limit the results
*
* @param limit The number of documents to return
*/
quickSample (
this: Mongoose.Aggregate<ResultType>,
limit: number
): Mongoose.Aggregate<ResultType>;
}
interface Query<ResultType, DocType, THelpers = {}, RawDocType = unknown, QueryOp = "find", TInstanceMethods = Record<string, never>> {
/**
* Sort the current query by `__seed` and limit the results
*
* @param limit The number of documents to return
*/
quickSample<RawDocTypeOverride extends { [ P in keyof RawDocType ]?: any } = {}> (
limit: number
): QueryWithHelpers<
IfEquals<
RawDocTypeOverride,
{},
ResultType,
ResultType extends any[]
? ResultType extends HydratedDocument<any>[]
? HydratedDocument<RawDocTypeOverride>[]
: RawDocTypeOverride[]
: (ResultType extends HydratedDocument<any>
? HydratedDocument<RawDocTypeOverride>
: RawDocTypeOverride) | (null extends ResultType ? null : never)
>,
DocType,
THelpers,
IfEquals<
RawDocTypeOverride,
{},
RawDocType,
RawDocTypeOverride
>,
QueryOp,
TInstanceMethods
>;
}
interface Schema {
/**
* Seed used by the QuickSample plugin to randomly sort results quickly and efficiently
*/
__seed: Mongoose.Schema.Types.Number;
}
}
export namespace QuickSample {
export type Type = {
/**
* Seed used by the QuickSample plugin to randomly sort results quickly and efficiently
*/
__seed: number;
};
/**
* Sort the current query by `__seed`, limit the results, then reset the seeds
*
* @param schema The schema to add the `__seed` field to
* @param options Additional type options for the `__seed` path
*/
export function Plugin<
SchemaType extends Mongoose.Schema<any, any, any, any, any>
> (
schema: SchemaType, {
autoInsert = true,
...options
}: Mongoose.SchemaTypeOptions<number> & {
/**
* Automatically insert `__seed` into any record that does not already have one
*/
autoInsert?: boolean;
} = {}
): void {
// Yoink!
const aggregateExec = Mongoose.Aggregate.prototype.exec;
const queryExec = Mongoose.Query.prototype.exec;
// Add the seed to the schema
schema.add({
__seed: {
default: () => Math.random(),
index: true,
...options,
type: Mongoose.Schema.Types.Number,
},
});
/**
* Sort the current query by `__seed` and limit the results
*
* @param limit The number of documents to limit to
*/
Mongoose.Aggregate.prototype.quickSample = function <ResultType> (
this: Mongoose.Aggregate<ResultType>,
limit: number = 50
): Mongoose.Aggregate<ResultType> {
return this.sort({ __seed: 1 }).limit(limit);
};
/**
* Executes the aggregate pipeline on the currently bound Model.
*/
Mongoose.Aggregate.prototype.exec = async function () {
// Call the executor super
const results = await aggregateExec.apply(this);
if (
// If we sorted by seed
this.pipeline().some(stage => "$sort" in stage && "__seed" in stage[ "$sort" ]) &&
// If we can reliably retrieve IDs for each item, reset their seeds
results && Array.isArray(results) && results.some(item => item._id !== undefined)
) {
await this.model()
.updateMany(autoInsert
? {
$or: [
{
_id: {
$in: results.map(item => item._id),
},
},
{
__seed: {
$in: [ null, "" ],
},
},
],
}
: {
_id: {
$in: results.map(item => item._id),
},
}, [
{
$set: {
__seed: {
$rand: {},
},
},
},
]);
}
return results;
};
/**
* Sort the current query by `__seed`, limit the results, then reset the seeds
*
* @param limit The number of documents to return
*/
schema.query.quickSample = function <ResultType, DocType> (
this: Mongoose.QueryWithHelpers<ResultType, DocType>,
limit: number = 50
) {
return this.sort({ __seed: 1 }).limit(limit);
};
/**
* Executes the query
*/
Mongoose.Query.prototype.exec = async function () {
// Call the executor super
const results = await queryExec.apply(this);
// Get query options
const options = this.getOptions();
if (
// If we sorted by seed
options.sort && "__seed" in options.sort &&
// If we can reliably retrieve IDs for each item, reset their seeds
results && Array.isArray(results) && results.some(item => item._id !== undefined)
) {
await this.model
.updateMany(autoInsert
? {
$or: [
{
_id: {
$in: results.map(item => item._id),
},
},
{
__seed: {
$in: [ null, "" ],
},
},
],
}
: {
_id: {
$in: results.map(item => item._id),
},
}, [
{
$set: {
__seed: {
$rand: {},
},
},
},
]);
}
return results;
};
}
}