-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.ts
232 lines (195 loc) · 5.24 KB
/
client.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
221
222
223
224
225
226
227
228
229
230
231
232
import type { AuthOptions } from "./auth_types.d.ts";
import { Document, EJSON } from "./deps.ts";
export interface MongoClientConstructorOptions {
dataSource: string;
auth: AuthOptions;
endpoint: string;
fetch?: typeof fetch;
}
export class MongoClient {
dataSource: string;
endpoint: string;
fetch = fetch;
headers = new Headers();
constructor(
{ dataSource, auth, endpoint, fetch: customFetch }:
MongoClientConstructorOptions,
) {
this.dataSource = dataSource;
this.endpoint = endpoint;
if (customFetch) {
this.fetch = customFetch;
}
this.headers.set("Content-Type", "application/ejson");
this.headers.set("Accept", "application/ejson");
if ("apiKey" in auth) {
this.headers.set("api-key", auth.apiKey);
return;
}
if ("jwtTokenString" in auth) {
this.headers.set("jwtTokenString", auth.jwtTokenString);
return;
}
if ("email" in auth && "password" in auth) {
this.headers.set("email", auth.email);
this.headers.set("password", auth.password);
return;
}
throw new Error("Invalid auth options");
}
database(name: string) {
return new Database(name, this);
}
}
export class Database {
name: string;
client: MongoClient;
constructor(name: string, client: MongoClient) {
this.name = name;
this.client = client;
}
collection<T = Document>(name: string) {
return new Collection<T>(name, this);
}
}
export class Collection<T> {
name: string;
database: Database;
client: MongoClient;
constructor(name: string, database: Database) {
this.name = name;
this.database = database;
this.client = database.client;
}
insertOne(doc: T): Promise<{ insertedId: string }> {
return this.callApi("insertOne", { document: doc });
}
insertMany(docs: T[]): Promise<{ insertedIds: string[] }> {
return this.callApi("insertMany", { documents: docs });
}
async findOne(
filter: Document,
{ projection }: { projection?: Document } = {},
): Promise<T> {
const result = await this.callApi("findOne", {
filter,
projection,
});
return result.document;
}
async find(
filter?: Document,
{ projection, sort, limit, skip }: {
projection?: Document;
sort?: Document;
limit?: number;
skip?: number;
} = {},
): Promise<T[]> {
const result = await this.callApi("find", {
filter,
projection,
sort,
limit,
skip,
});
return result.documents;
}
updateOne(
filter: Document,
update: Document,
{ upsert }: { upsert?: boolean } = {},
): Promise<
{ matchedCount: number; modifiedCount: number; upsertedId?: string }
> {
return this.callApi("updateOne", {
filter,
update,
upsert,
});
}
updateMany(
filter: Document,
update: Document,
{ upsert }: { upsert?: boolean } = {},
): Promise<
{ matchedCount: number; modifiedCount: number; upsertedId?: string }
> {
return this.callApi("updateMany", {
filter,
update,
upsert,
});
}
replaceOne(
filter: Document,
replacement: Document,
{ upsert }: { upsert?: boolean } = {},
): Promise<
{ matchedCount: number; modifiedCount: number; upsertedId?: string }
> {
return this.callApi("replaceOne", {
filter,
replacement,
upsert,
});
}
deleteOne(filter: Document): Promise<{ deletedCount: number }> {
return this.callApi("deleteOne", { filter });
}
deleteMany(filter: Document): Promise<{ deletedCount: number }> {
return this.callApi("deleteMany", { filter });
}
async aggregate<T = Document>(pipeline: Document[]): Promise<T[]> {
const result = await this.callApi("aggregate", { pipeline });
return result.documents;
}
async countDocuments(
filter?: Document,
options?: { limit?: number; skip?: number },
): Promise<number> {
const pipeline: Document[] = [];
if (filter) {
pipeline.push({ $match: filter });
}
if (typeof options?.skip === "number") {
pipeline.push({ $skip: options.skip });
}
if (typeof options?.limit === "number") {
pipeline.push({ $limit: options.limit });
}
pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } });
const [result] = await this.aggregate<{ n: number }>(pipeline);
if (result) return result.n;
return 0;
}
async estimatedDocumentCount(): Promise<number> {
const pipeline = [
{ $collStats: { count: {} } },
{ $group: { _id: 1, n: { $sum: "$count" } } },
];
const [result] = await this.aggregate<{ n: number }>(pipeline);
if (result) return result.n;
return 0;
}
// deno-lint-ignore no-explicit-any
async callApi(method: string, extra: Document): Promise<any> {
const { endpoint, dataSource, headers } = this.client;
const url = `${endpoint}/action/${method}`;
const response = await this.client.fetch(url, {
method: "POST",
headers,
body: EJSON.stringify({
collection: this.name,
database: this.database.name,
dataSource: dataSource,
...extra,
}),
});
const body = await response.text();
if (!response.ok) {
throw new Error(`${response.statusText}: ${body}`);
}
return EJSON.parse(body);
}
}