-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.ts
298 lines (267 loc) · 8.46 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
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
import _axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import type { Filter, FindOptions, Sort, UpdateFilter, Document } from 'mongodb'
// https://github.com/surmon-china/mongodb-data-api/pull/3/files @maxfi
type Projection = FindOptions['projection']
// https://github.com/surmon-china/mongodb-data-api/pull/4/files @maxfi
type NoInfer<A extends any> = [A][A extends any ? 0 : never]
type AnyKeys<T> = { [P in keyof T]?: T[P] | any }
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR<T, U> = T | U extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U
type ExtendBaseParams<T> = BaseParams & T
interface BaseParams {
dataSource?: string
database?: string
collection?: string
[key: string]: any
}
interface BaseConfig {
/**
* Specific Data API key.
* @link https://www.mongodb.com/docs/atlas/api/data-api/#2.-create-a-data-api-key
*/
apiKey: string
}
interface UrlEndpointConfig extends BaseConfig {
/**
* Specific URL Endpoint.
* @link https://www.mongodb.com/docs/atlas/api/data-api/#3.-send-a-data-api-request
*/
urlEndpoint: string
}
interface PackEndpointConfig extends BaseConfig {
/**
* Specific Data App ID.
* @link https://www.mongodb.com/docs/atlas/api/data-api/#3.-send-a-data-api-request
*/
appId: string
/**
* Specific region name of endpoint.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#regional-requests
*/
region?: string
/**
* Specific cloud provider of endpoint.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#regional-requests
*/
cloud?: string
}
export type Config = XOR<UrlEndpointConfig, PackEndpointConfig>
export class MongoDBDataAPI<InnerDoc = Document> {
#config: Config
#baseParams: BaseParams
#axios: AxiosInstance
constructor(config: Config, baseParams?: BaseParams, axios?: AxiosInstance) {
if (!config.apiKey) {
throw new Error('Invalid API key!')
}
this.#config = config
this.#baseParams = baseParams || {}
this.#axios = axios || _axios.create()
}
#newAPI<D>(params: BaseParams) {
return new MongoDBDataAPI<D>(
{ ...this.#config },
{
...this.#baseParams,
...params
}
)
}
/** Select a cluster. */
public $cluster(clusterName: string) {
return this.#newAPI<InnerDoc>({ dataSource: clusterName }) as Omit<
MongoDBDataAPI<InnerDoc>,
'$cluster' | '$collection'
>
}
/** Select a database. */
public $database(database: string) {
return this.#newAPI<InnerDoc>({ database }) as Omit<
MongoDBDataAPI<InnerDoc>,
'$cluster' | '$database'
>
}
/** Select a collection. */
public $collection<Doc = InnerDoc>(collection: string) {
return this.#newAPI<Doc>({ collection }) as Omit<
MongoDBDataAPI<Doc>,
'$cluster' | '$database' | '$collection'
>
}
/**
* Execute a API action.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/
*/
public $$action<Result = unknown>(
type: string,
params: BaseParams = {},
axiosConfig?: AxiosRequestConfig
): Promise<Result> {
const mergedParams = {
...this.#baseParams,
...params
}
if (!mergedParams.dataSource || !mergedParams.database || !mergedParams.collection) {
return Promise.reject('Invalid params: dataSource, database, collection')
}
// https://www.mongodb.com/docs/atlas/api/data-api-resources/#base-url
// https://www.mongodb.com/docs/atlas/api/data-api-resources/#regional-requests
const getUrlEndpoint = (appId: string, region?: string, cloud?: string) => {
return region && cloud
? `https://${region}.${cloud}.data.mongodb-api.com/app/${appId}/endpoint/data/v1`
: `https://data.mongodb-api.com/app/${appId}/endpoint/data/v1`
}
const getActionUrl = (endpoint: string, action: string) => {
return `${endpoint}/action/${action}`
}
return this.#axios({
method: 'post',
data: JSON.stringify(mergedParams),
url: this.#config.urlEndpoint
? getActionUrl(this.#config.urlEndpoint, type)
: getActionUrl(
getUrlEndpoint(this.#config.appId!, this.#config.region, this.#config.cloud),
type
),
headers: {
'Content-Type': 'application/json',
'Access-Control-Request-Headers': '*',
'api-key': this.#config.apiKey
},
...axiosConfig
})
.then((response) => {
return response.data
})
.catch((error) => {
// https://www.mongodb.com/docs/atlas/api/data-api-resources/#error-codes
return Promise.reject(_axios.isAxiosError(error) ? error.toJSON() : error)
})
}
/**
* Find a Single Document.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#find-a-single-document
*/
public findOne<D = InnerDoc, T = NoInfer<D>>(
params?: ExtendBaseParams<{
filter?: Filter<T>
projection?: Projection
}>
) {
return this.$$action<{ document: D | null }>('findOne', params)
}
/**
* Find Multiple Documents.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#find-multiple-documents
*/
public find<D = InnerDoc, T = NoInfer<D>>(
params?: ExtendBaseParams<{
filter?: Filter<T>
projection?: Projection
sort?: Sort
limit?: number
skip?: number
}>
) {
return this.$$action<{ documents: Array<D> }>('find', params)
}
/**
* Insert a Single Document.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#insert-a-single-document
*/
public insertOne<D = InnerDoc, T = NoInfer<D>>(
params: ExtendBaseParams<{ document: AnyKeys<T> | Document }>
) {
return this.$$action<{ insertedId: string }>('insertOne', params)
}
/**
* Insert Multiple Documents.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#insert-multiple-documents
*/
public insertMany<D = InnerDoc, T = NoInfer<D>>(
params: ExtendBaseParams<{ documents: Array<AnyKeys<T> | Document> }>
) {
return this.$$action<{ insertedIds: Array<string> }>('insertMany', params)
}
/**
* Update a Single Document.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#update-a-single-document
*/
public updateOne<D = InnerDoc, T = NoInfer<D>>(
params: ExtendBaseParams<{
filter: Filter<T>
update: UpdateFilter<T>
upsert?: boolean
}>
) {
return this.$$action<{
matchedCount: number
modifiedCount: number
upsertedId?: string
}>('updateOne', params)
}
/**
* Update Multiple Documents.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#update-multiple-documents
*/
public updateMany<D = InnerDoc, T = NoInfer<D>>(
params: ExtendBaseParams<{
filter: Filter<T>
update: UpdateFilter<T>
upsert?: boolean
}>
) {
return this.$$action<{
matchedCount: number
modifiedCount: number
upsertedId?: string
}>('updateMany', params)
}
/**
* Replace a Single Document.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#replace-a-single-document
*/
public replaceOne<D = InnerDoc, T = NoInfer<D>>(
params: ExtendBaseParams<{
filter: Filter<T>
replacement: any
upsert?: boolean
}>
) {
return this.$$action<{
matchedCount: number
modifiedCount: number
upsertedId?: string
}>('replaceOne', params)
}
/**
* Delete a Single Document.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#delete-a-single-document
*/
public deleteOne<D = InnerDoc, T = NoInfer<D>>(
params: ExtendBaseParams<{ filter: Filter<T> }>
) {
return this.$$action<{ deletedCount: number }>('deleteOne', params)
}
/**
* Delete Multiple Documents.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#delete-multiple-documents
*/
public deleteMany<D = InnerDoc, T = NoInfer<D>>(
params: ExtendBaseParams<{ filter: Filter<T> }>
) {
return this.$$action<{ deletedCount: number }>('deleteMany', params)
}
/**
* Run an Aggregation Pipeline.
* @link https://www.mongodb.com/docs/atlas/api/data-api-resources/#run-an-aggregation-pipeline
*/
public aggregate<T extends Array<any>>(
params: ExtendBaseParams<{ pipeline: Array<Document> }>
) {
return this.$$action<{ documents: T }>('aggregate', params)
}
}
export const createMongoDBDataAPI = (config: Config, axios?: AxiosInstance) => {
return new MongoDBDataAPI(config, void 0, axios)
}