-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.server.ts
82 lines (74 loc) · 2.27 KB
/
utils.server.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
import { AggregateOptions, Collection, Document } from "mongodb";
import { getDB } from "./dbConnect";
type ProxyCollection<TSchema extends Document> = Pick<
Collection<TSchema>,
| "distinct"
| "find"
| "findOne"
| "updateOne"
| "insertOne"
| "countDocuments"
| "updateMany"
| "deleteMany"
| "insertMany"
| "createIndexes"
| "aggregate"
>;
export function proxyCollection<
TSchema extends Document,
PCollection extends ProxyCollection<TSchema> = ProxyCollection<TSchema>,
>(name: string) {
return new Proxy({} as PCollection, {
// @ts-expect-error - ?
get<K extends keyof PCollection>(_target: unknown, property: K) {
if (property === "find") {
return function (...args: Parameters<PCollection["find"]>) {
return {
async *[Symbol.asyncIterator]() {
const DB = await getDB();
// @ts-expect-error - ?
for await (const document of DB.collection(name).find(...args)) {
yield document;
}
},
async toArray() {
const DB = await getDB();
return (
DB.collection(name)
// @ts-expect-error - ?
.find(...args)
.toArray()
);
},
};
};
}
if (property === "aggregate") {
return function (pipeline?: Document[], options?: AggregateOptions) {
return {
async *[Symbol.asyncIterator]() {
const DB = await getDB();
for await (const document of DB.collection(name).aggregate(
pipeline,
options,
)) {
yield document;
}
},
async toArray() {
const DB = await getDB();
return DB.collection(name).aggregate(pipeline, options).toArray();
},
};
};
}
// @ts-expect-error - ?
return async function (...args: Parameters<PCollection[K]>) {
const DB = await getDB();
// @ts-expect-error - ?
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call
return DB.collection(name)[property](...args);
};
},
});
}