This repository was archived by the owner on Sep 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
381 lines (364 loc) · 10.3 KB
/
Copy pathmain.ts
File metadata and controls
381 lines (364 loc) · 10.3 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import type {
BasicEndpoints,
DatabaseConfig,
Headers,
Query,
SendDBRequestFunction,
} from "./types.ts";
/**
* Error class representing a failure in the MongoDB request.
* This error is thrown when a request to the database fails for any reason.
*
* @example
* const createDBRequest = createSendDBRequestFunction(config);
*
* try {
* const dbRequest = new MongoDBRequest();
* dbRequest.endpoint = '/find';
* dbRequest.query = {
* collection: 'books'
* }
* await sendDBRequest(dbRequest); // Error!
* } catch(error) {
* if (error instanceof MRHRequestError) {
* console.error(error.name); // => MRHRequestError
* console.error(error.message);
* // =>
* // Error: Database request failed <Error message from MongoDB server>
* // Endpoint: '/find'
* // Query: "{ 'collection': 'books' }"
*
* console.error(error.endpoint); // => '/find'
* console.error(error.query); // => { collection: "books" }
* console.error(error.mongoErrorMessage); // => Error message from MongoDB
* }
* }
*/
export class MRHRequestError extends Error {
constructor(
public endpoint: string,
public query: Query,
public mongoErrorMessage: string,
) {
super(
`Error: Database request failed ${mongoErrorMessage}\nEndpoint: ${endpoint}\Query: ${
JSON.stringify(
query,
)
}`,
);
this.name = this.constructor.name;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
/**
* Error class representing a missing required parameter error.
* This error is thrown when a required parameter is missing from the MongoDB request.
*
* @example
* const sendDBRequest = createSendDBRequestFunction(config);
*
* try {
* const dbRequest = new MongoDBRequest();
* // MRHMissingParameterError is thrown because the endpoint is not set.
* dbRequest.endpoint = null;
*
* // MRHMissingParameterError is thrown because the query is not set.
* // The query check occurs after the endpoint check.
* // So in this example, an endpoint error will be thrown.
* dbRequest.query = {};
*
* await sendDBRequest(dbRequest);
* } catch (error) {
* if (error instanceof MRHMissingParameterError) {
* console.error(error.name); // => Error: MRHMissingParameterError
* console.error(error.message); // => Error: Missing required paramter: Endpoint
* }
* }
*/
export class MRHMissingParameterError extends Error {
constructor(parameter: "Endpoint" | "Query") {
super(`Error: Missing required parameter: ${parameter}`);
this.name = this.constructor.name;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
/**
* Represents a MongoDB request, allowing configuration of the endpoint and query.
* This class serves as a base for creating MongoDB API requests, providing the
* ability to set and get the endpoint, base query, and additional query parameters.
*
* @template T - A string literal type representing the allowed endpoints for the request.
*
* ### Basic usage:
*
* Example:
*
* ```ts
* // Setup:
* // Define your databaseConfig somewhere in your files
* // and prepare your functions to send database requests.
* // config.ts
* const config: DatabaseConfig = {
* dataSource: '...'.
* database: '...',
* baseUrl: '...',
* apiKey: '...'
* };
*
* const sendDBRequset = createSendDBRequestFunction(config);
*
* // books.ts
* // 1. Create instance
* const dbRequest = new MongoDBRequest();
*
* // 2. Set endpoint
* dbRequest.endpoint = '/find'
*
* // 3. Set query
* dbRequest.query = { collection: 'books' };
*
* // 4. Send request!
* const result = sendDBRequest(dbReqeust);
* // result.documents = [...some book documents]
* ```
*
* ### Advanced topics:
*
* Custom reqeust class:
*
* If you have duplicate queries, you can resolve them by extending this class.
*
* Example:
*
* ```ts
* class BookCollectionRequest extends MongoDBRequest {
* constructor() {
* super();
* this.baseQuery = {
* collection: 'books'
* }
* }
* }
*
* const bookRequest = new BookCollectionRequest();
*
* bookRequest.endpoint = '/findOne';
*
* bookRequest.query = { filter: { _id: { $oid: '123' } } };
*
* console.log(bookRequest.fullQuery);
* // Output: { collection: 'books', filter: { _id: '123' } }
* ```
*/
export class MongoDBRequest<T extends BasicEndpoints = BasicEndpoints> {
/**
* The endpoint for the MongoDB API request.
* Should be set to the appropriate endpoint such as '/find', '/findOne', etc.
*
* If you want to add your own endpoint type to the endpoint property, pass it a generic type in the MongoDBRequest class.
*
* @example
* type CustomEndpoints = BasicEndpoints | '/custom-endpoint'
*
* const dbRequest = new MongoDBRequest<CustomEndpoints>();
*
* dbRequest.endpoint = '/custom-endpoint'; // endpoint property is type safe!
*/
endpoint: T | null = null;
/**
* The base query parameters for the request.
* This can include common parameters that are reused across multiple requests.
*/
#baseQuery: Query = {};
/**
* The specific query parameters for the request.
* These can override or extend the base query parameters.
*/
query: Query = {};
/**
* The headers for the MongoDB API request.
*
* @example
* async function getUserProfile(ctx) {
* // Those function is fake.
* const accessToken = getAccessToken(ctx);
* const userId = getUserId(ctx);
*
* const dbRequest = new MongoDBRequest();
*
* dbRequest.query = {
* collection: 'users',
* filter: { _id: { $oid: userId }}
* };
*
* dbRequest.headers = { Authorization: `Bearer ${accessToken}` };
*
* const result = await sendDBRequest(dbRequest);
*
* const user = result.document;
*
* return user;
* }
*/
headers: Headers = {};
/**
* Sets the base query parameters for the request.
* These parameters are merged with the current base query.
*
* @example
* class BookCollectionRequest extends MongoDBRequest {
* constructor() {
* super();
* this.baseQuery = {
* collection: 'books'
* }
* }
* }
*
* const bookCollectionRequest = new BookCollectionRequest();
*
* bookCollectionRequest.endpoint = '/findOne';
*
* bookCollectionRequest.query = { filter: { $oid: '123' }};
*
* const book = await sendDBRequest(bookCollectionRequest);
*/
set baseQuery(newBaseQuery: Query) {
this.#baseQuery = { ...this.#baseQuery, ...newBaseQuery };
}
/**
* Gets the current base query parameters.
*
* @example
* class BookCollectionRequest extends MongoDBRequest {
* constructor() {
* super();
* this.baseQuery = {
* collection: 'books'
* }
* }
* };
*
* const bookCollectionRequest = new BookCollectionRequest();
*
* bookCollectionRequest.endpoint = '/findOne';
*
* bookCollectionRequest.query = {
* filter: { _id: { $oid: '123' } }
* };
*
* console.log(bookCollectionRequest.baseQuery);
* // => { collection: 'books', filter: { _id: { $oid: '123' } } }
*/
get baseQuery(): Query {
return this.#baseQuery;
}
/**
* Computes the full query by combining the base query and the specific query parameters.
*
* @example
* class BookCollectionRequest extends MongoDBRequest {
* protected _baseQuery = { collection: 'books' }
* }
*
* const bookCollectionRequest = new BookCollectionRequest();
*
* bookCollectionRequest.fullQuery // => { collection: 'books' }
*
* bookCollectionRequest.query = {
* filter: { _id: { $oid: '123' } }
* };
*
* bookCollectionRequest.fullQuery;
* // => { collection: 'books', filter: { $ oid: '123' }}
*/
get fullQuery(): Query {
return { ...this.baseQuery, ...this.query };
}
}
/**
* Creates a function to send MongoDB requests with a specific configuration.
*
* This function configures the necessary settings for sending a request to a MongoDB database,
* including the base URL, data source, database name, and API key.
* It returns a function that can be used to send requests with specific MongoDBRequest instances.
*
* For more information on the values for each database configuration, see the [Getting Started with Deno & MongoDB](https://www.mongodb.com/developer/languages/javascript/getting-started-deno-mongodb/) video.
*
* @throws {MRHMissingParameterError} Throws an error if the request endpoint or query is missing.
* @throws {MRHRequestError} Throws an error if the request fails due to a MongoDB server error.
*
* @example
* const config: DatabaseConfig = {
* baseUrl: '...',
* dataSource: '...',
* database: '...',
* apiKey: '...'
* };
*
* const sendDBRequest = createSendDBRequestFunction(config);
*
* try {
* const dbRequest = new MongoDBRequest();
*
* dbRequest.endpoint = '/find';
* dbRequest.query = { collection: 'books' };
*
* const result = await sendDBRequest(dbRequest);
* console.log(result.documents);
* } catch (error) {
* if (error instanceof MRHMissingParameterError) {
* console.error(error.message);
* }
* if (error instanceof MRHRequestError) {
* console.error(error.message);
* } else {
* console.error('An unexpected error occurred:', error);
* }
* }
*/
export function createSendDBRequestFunction({
baseUrl,
dataSource,
database,
apiKey,
}: DatabaseConfig): SendDBRequestFunction {
return async function sendDBRequest<T>(request: MongoDBRequest): Promise<T> {
if (!request.endpoint) {
throw new MRHMissingParameterError("Endpoint");
}
if (!isExistQuery(request.fullQuery)) {
throw new MRHMissingParameterError("Query");
}
const url = baseUrl + request.endpoint;
const query = {
dataSource,
database,
...request.fullQuery,
};
const requestInit: RequestInit = {
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key": apiKey,
...request.headers,
},
body: JSON.stringify(query),
};
try {
const response = await fetch(url, requestInit);
const result = await response.json();
return result;
} catch (error) {
throw new MRHRequestError(request.endpoint, request.fullQuery, error);
}
};
}
function isExistQuery(query: Query): boolean {
return Object.keys(query).length > 0;
}