@pi-r/atlas 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2023 An Pham
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ ### @pi-r/atlas
2
+
3
+ ### LICENSE
4
+
5
+ MIT
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getObjectId = exports.executeBatchQuery = exports.executeQuery = exports.createDatabaseClient = exports.validateDatabase = void 0;
4
+ const types_1 = require("@e-mc/types");
5
+ const util_1 = require("@e-mc/cloud/util");
6
+ const mongodb_1 = require("@pi-r/mongodb");
7
+ const Module = require("@e-mc/module");
8
+ const MONGODB_V3 = Module.checkSemVer('mongodb', 1, 4);
9
+ function sanitizeCredentials(item, credential) {
10
+ const { username, password } = credential;
11
+ if (username) {
12
+ const auth = password ? { username, password } : { username };
13
+ if (MONGODB_V3) {
14
+ credential.auth = password || !credential.auth || !credential.auth.password ? auth : credential.auth;
15
+ }
16
+ else {
17
+ credential.auth || (credential.auth = auth);
18
+ }
19
+ delete credential.username;
20
+ }
21
+ if (password) {
22
+ delete credential.password;
23
+ }
24
+ if (MONGODB_V3 && credential.auth) {
25
+ if (!(0, util_1.hasBasicAuth)(item.uri)) {
26
+ const auth = (0, util_1.getBasicAuth)(credential.auth);
27
+ if (auth) {
28
+ const url = item.uri.split('://');
29
+ item.uri = url[0] + '://' + auth + url[1];
30
+ }
31
+ }
32
+ delete credential.auth;
33
+ }
34
+ }
35
+ function validateDatabase(credential, data) {
36
+ const auth = credential.auth;
37
+ return !!(data.table && (auth?.username || credential.username || Module.isURL(data.uri) && (0, util_1.hasBasicAuth)(data.uri)));
38
+ }
39
+ exports.validateDatabase = validateDatabase;
40
+ function createDatabaseClient(credential, data) {
41
+ try {
42
+ sanitizeCredentials(data, credential);
43
+ const { MongoClient } = require('mongodb');
44
+ return new MongoClient(data.uri, credential);
45
+ }
46
+ catch (err) {
47
+ this.checkPackage(err, 'mongodb', { passThrough: true });
48
+ throw err;
49
+ }
50
+ }
51
+ exports.createDatabaseClient = createDatabaseClient;
52
+ async function executeQuery(credential, data, sessionKey) {
53
+ return (await executeBatchQuery.call(this, credential, [data], sessionKey))[0] || [];
54
+ }
55
+ exports.executeQuery = executeQuery;
56
+ async function executeBatchQuery(credential, batch, sessionKey) {
57
+ const length = batch.length;
58
+ const result = new Array(length);
59
+ const clients = {};
60
+ const caching = length > 0 && this.hasCache(batch[0].service, sessionKey);
61
+ const coercing = this.hasCoerce('atlas', 'options');
62
+ const cacheValue = { value: this.valueOfKey(credential, 'cache'), sessionKey };
63
+ const createClient = async (item, options) => {
64
+ var _a;
65
+ return clients[_a = item.uri + Module.asString(options, true)] || (clients[_a] = await createDatabaseClient.call(this, options, item).connect());
66
+ };
67
+ const closeClient = () => {
68
+ for (const key in clients) {
69
+ clients[key].close();
70
+ }
71
+ };
72
+ for (let i = 0; i < length; ++i) {
73
+ const item = batch[i];
74
+ const { service, name, table, id, aggregate, sort, client, ignoreCache } = item;
75
+ if (!table) {
76
+ closeClient();
77
+ throw (0, util_1.formatError)(item, "Missing database table" /* ERR_DB.TABLE */);
78
+ }
79
+ let { query, update, limit = 0 } = item;
80
+ if (id && (!query || limit === 1)) {
81
+ query = getObjectId(id);
82
+ limit = 1;
83
+ }
84
+ const renewCache = ignoreCache === 0;
85
+ const options = item.options ? length === 1 && !MONGODB_V3 ? Object.assign(item.options, credential) : { ...item.options, ...credential } : length === 1 && !MONGODB_V3 ? credential : { ...credential };
86
+ let rows, queryString = caching && ignoreCache !== true || ignoreCache === false || ignoreCache === 1 || renewCache ? (name || '') + '_' + table + '_' + limit + Module.asString(options, true) + (sort ? Module.asString(sort, true) : '') + (client ? Module.asString(client, true) : '') : '', auth, pipeline;
87
+ if (queryString) {
88
+ sanitizeCredentials(item, options);
89
+ auth = { uri: item.uri, options };
90
+ }
91
+ const getCache = () => {
92
+ if (ignoreCache === 1) {
93
+ return;
94
+ }
95
+ cacheValue.renewCache = renewCache;
96
+ return this.getQueryResult(service, auth, queryString, cacheValue);
97
+ };
98
+ const getCollection = (mongoClient) => mongoClient.db(name, client?.db).collection(table, client?.collection);
99
+ if (aggregate) {
100
+ pipeline = Array.isArray(aggregate) ? aggregate : aggregate.pipeline;
101
+ }
102
+ if (pipeline || query) {
103
+ if (queryString) {
104
+ queryString += Module.asString(aggregate || query, true);
105
+ if ((aggregate || !update) && (rows = getCache())) {
106
+ result[i] = rows;
107
+ continue;
108
+ }
109
+ }
110
+ const collection = getCollection(await createClient(item, options));
111
+ if (pipeline) {
112
+ const aggregateOptions = aggregate?.options;
113
+ if (coercing) {
114
+ pipeline.forEach(doc => (0, types_1.coerceObject)(doc));
115
+ if (aggregateOptions) {
116
+ (0, types_1.coerceObject)(aggregateOptions);
117
+ }
118
+ }
119
+ const items = collection.aggregate(pipeline, aggregateOptions);
120
+ if (sort) {
121
+ items.sort((0, mongodb_1.getSortValue)(sort, coercing)[0]);
122
+ }
123
+ if (limit > 0) {
124
+ items.limit(limit);
125
+ }
126
+ rows = await items.toArray();
127
+ }
128
+ else {
129
+ const updateType = item.updateType;
130
+ const [filter, command] = (0, mongodb_1.getFilterValue)(query, coercing);
131
+ if (update && coercing) {
132
+ (0, types_1.coerceObject)(update);
133
+ }
134
+ if ((0, types_1.isArray)(update)) {
135
+ const insertOptions = item.execute?.insert;
136
+ if (insertOptions) {
137
+ await collection.insertMany(update, coercing ? (0, types_1.coerceObject)(insertOptions) : insertOptions);
138
+ }
139
+ else {
140
+ await collection.insertMany(update);
141
+ }
142
+ update = undefined;
143
+ }
144
+ else if (updateType === 1) {
145
+ update = undefined;
146
+ }
147
+ if (limit === 1) {
148
+ const document = update ? await collection[updateType === 2 ? 'findOneAndReplace' : updateType === 3 ? 'findOneAndDelete' : 'findOneAndUpdate'](filter, update, command) : await collection.findOne(filter, command);
149
+ rows = document ? [document] : [];
150
+ }
151
+ else {
152
+ if (update) {
153
+ await collection.updateMany(filter, update);
154
+ }
155
+ const items = collection.find(filter, command);
156
+ if (sort) {
157
+ items.sort(...(0, mongodb_1.getSortValue)(sort, coercing));
158
+ }
159
+ if (limit > 1) {
160
+ items.limit(limit);
161
+ }
162
+ rows = await items.toArray();
163
+ }
164
+ }
165
+ }
166
+ else if (!aggregate) {
167
+ if (queryString && (rows = getCache())) {
168
+ result[i] = rows;
169
+ continue;
170
+ }
171
+ const items = getCollection(await createClient(item, options)).find();
172
+ if (sort) {
173
+ items.sort(...(0, mongodb_1.getSortValue)(sort, coercing));
174
+ }
175
+ if (limit > 0) {
176
+ items.limit(limit);
177
+ }
178
+ rows = await items.toArray();
179
+ }
180
+ else {
181
+ queryString = '';
182
+ }
183
+ result[i] = this.setQueryResult(service, auth, queryString, rows, cacheValue);
184
+ }
185
+ closeClient();
186
+ return result;
187
+ }
188
+ exports.executeBatchQuery = executeBatchQuery;
189
+ function getObjectId(value) {
190
+ const { ObjectId } = require('mongodb');
191
+ return { '_id': new ObjectId(value) };
192
+ }
193
+ exports.getObjectId = getObjectId;
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@pi-r/atlas",
3
+ "version": "0.0.1",
4
+ "description": "MongoDB Atlas cloud functions for E-mc.",
5
+ "main": "client/index.js",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/anpham6/pi-r.git",
12
+ "directory": "src/cloud/atlas"
13
+ },
14
+ "keywords": [
15
+ "squared",
16
+ "e-mc",
17
+ "squared-functions"
18
+ ],
19
+ "author": "An Pham <anpham6@gmail.com>",
20
+ "license": "MIT",
21
+ "homepage": "https://github.com/anpham6/pi-r#readme",
22
+ "dependencies": {
23
+ "@e-mc/cloud": "^0.4.0",
24
+ "@e-mc/db": "^0.4.0",
25
+ "@e-mc/module": "^0.4.0",
26
+ "@e-mc/types": "^0.4.0",
27
+ "@pi-r/mongodb": "^0.0.1",
28
+ "mongodb": "^5.1.0"
29
+ }
30
+ }