blackcat.js-database 1.0.0-test
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/README.md +3 -0
- package/dist/index.d.mts +751 -0
- package/dist/index.d.ts +751 -0
- package/dist/index.js +995 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +969 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +36 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,995 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
22
|
+
|
|
23
|
+
// src/index.ts
|
|
24
|
+
var index_exports = {};
|
|
25
|
+
__export(index_exports, {
|
|
26
|
+
Database: () => Database,
|
|
27
|
+
JSONDriver: () => JSONDriver
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(index_exports);
|
|
30
|
+
|
|
31
|
+
// src/utils/isObject.function.ts
|
|
32
|
+
var isObject = /* @__PURE__ */ __name((item) => !Array.isArray(item) && item !== null && typeof item == "object", "isObject");
|
|
33
|
+
|
|
34
|
+
// src/utils/typeOf.function.ts
|
|
35
|
+
var typeOf = /* @__PURE__ */ __name((input) => {
|
|
36
|
+
if (input == null || typeof input === "number" && Number.isNaN(input)) return String(input);
|
|
37
|
+
if (typeof input === "function" && input.prototype) return `${input.name} class instance`;
|
|
38
|
+
return input?.constructor?.name ?? typeof input;
|
|
39
|
+
}, "typeOf");
|
|
40
|
+
|
|
41
|
+
// src/utils/isNumber.function.ts
|
|
42
|
+
var isNumber = /* @__PURE__ */ __name((input) => !isNaN(input) && input !== "" && input !== null && typeOf(input) !== "Array", "isNumber");
|
|
43
|
+
|
|
44
|
+
// src/utils/BlackCatError.ts
|
|
45
|
+
var errors = {
|
|
46
|
+
DEVICE_IS_OFFLINE: "Your device appears to be offline so it's impossible to proceed with connection to your online MongoDB cluster. Please connect your device to the internet or switch to the local MongoDB database and try again.",
|
|
47
|
+
CONNECTION_NOT_ESTABLISHED: "Failed to connect to MongoDB. Please double-check the specified connection URI and make sure that you're performing the database connection using the `QuickMongoClient.connect()` method.",
|
|
48
|
+
CONNECTION_URI_NOT_SPECIFIED: "The MongoDB connection URI must be specified.",
|
|
49
|
+
INVALID_CONNECTION_URI: "The specified MongoDB connection URI is invalid.",
|
|
50
|
+
UNKNOWN_ERROR: "Unknown error.",
|
|
51
|
+
REQUIRED_PARAMETER_MISSING: "'{1}' parameter is required but is missing.",
|
|
52
|
+
REQUIRED_CONSTRUCTOR_PARAMETER_MISSING: "'{1}' parameter in constructor '{2}' is required but is missing.",
|
|
53
|
+
INVALID_CONSTRUCTOR_PARAMETER_TYPE: "'{1}' parameter in constructor '{2}' must be a type of {3}. Received type: {4}.",
|
|
54
|
+
INVALID_TYPE: "'{1}' must be a type of {2}. Received type: {3}.",
|
|
55
|
+
ONE_OR_MORE_ARRAY_TYPES_INVALID: "All specified elements from array in '{1}' parameter must be a type of {2}. Received array of types: {3}.",
|
|
56
|
+
INVALID_TARGET: "The target in database must be a type of {1}. Received target type: {2}.",
|
|
57
|
+
INVALID_KEY: "{1}",
|
|
58
|
+
INVALID_PARAMETER: "{1} {2}",
|
|
59
|
+
DATABASE_CONNECTION_FAILED: "{1}"
|
|
60
|
+
};
|
|
61
|
+
var createTypesArray = /* @__PURE__ */ __name((...elements) => `[${elements.map((element) => typeOf(element))}]`, "createTypesArray");
|
|
62
|
+
var _BlackCatError = class _BlackCatError extends Error {
|
|
63
|
+
/**
|
|
64
|
+
* Creates a BlackCatError instance.
|
|
65
|
+
* @param {string} errorCode Quick Mongo error code.
|
|
66
|
+
* @param {any[]} params Additional parameters to replace the placeholders in the error message.
|
|
67
|
+
*/
|
|
68
|
+
constructor(errorCode, ...params) {
|
|
69
|
+
const code = errors[errorCode] ? errorCode : "UNKNOWN_ERROR";
|
|
70
|
+
let message = errors[code];
|
|
71
|
+
for (let i = 0; i < params.length; i++) {
|
|
72
|
+
message = message.replaceAll(`{${i + 1}}`, params[i]);
|
|
73
|
+
}
|
|
74
|
+
;
|
|
75
|
+
super(message);
|
|
76
|
+
this.name = `BlackCatError [${code}]`;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
__name(_BlackCatError, "BlackCatError");
|
|
80
|
+
var BlackCatError = _BlackCatError;
|
|
81
|
+
|
|
82
|
+
// src/utils/TypedObject.ts
|
|
83
|
+
var _TypedObject = class _TypedObject {
|
|
84
|
+
/**
|
|
85
|
+
* Returns the names of the enumerable string properties and methods of an object.
|
|
86
|
+
*
|
|
87
|
+
* Type parameters:
|
|
88
|
+
*
|
|
89
|
+
* - `TObject` (`Record<string, any>`) - The object to get the object keys types from.
|
|
90
|
+
*
|
|
91
|
+
* @param {TObject} obj Object to get the keys from.
|
|
92
|
+
*
|
|
93
|
+
* @returns {Array<ExtractObjectKeys<TObject>>}
|
|
94
|
+
* Array of names of the enumerable string properties and methods of the specified object.
|
|
95
|
+
*/
|
|
96
|
+
static keys(obj) {
|
|
97
|
+
return Object.keys(obj || {});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Returns an array of values of the enumerable properties of an object.
|
|
101
|
+
*
|
|
102
|
+
* Type parameters:
|
|
103
|
+
*
|
|
104
|
+
* - `TObject` (`Record<string, any>`) - The object to get the object values types from.
|
|
105
|
+
*
|
|
106
|
+
* @param {TObject} obj Object to get the values from.
|
|
107
|
+
*
|
|
108
|
+
* @returns {Array<ExtractObjectValues<TObject>>}
|
|
109
|
+
* Array of values of the enumerable properties of the specified object.
|
|
110
|
+
*/
|
|
111
|
+
static values(obj) {
|
|
112
|
+
return Object.values(obj || {});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Returns an array of entries (key-value pairs) of the enumerable properties of an object.
|
|
116
|
+
*
|
|
117
|
+
* Type parameters:
|
|
118
|
+
*
|
|
119
|
+
* - `TObject` (`Record<string, any>`) - The object to get the object entries types (key-value pairs types) from.
|
|
120
|
+
*
|
|
121
|
+
* @param {TObject} obj Object to get the entries from.
|
|
122
|
+
*
|
|
123
|
+
* @returns {ExtractObjectEntries<TObject>[]}
|
|
124
|
+
* Array of entries (key-value pairs) of the enumerable properties of the specified object.
|
|
125
|
+
*/
|
|
126
|
+
static entries(obj) {
|
|
127
|
+
return Object.entries(obj || {});
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
__name(_TypedObject, "TypedObject");
|
|
131
|
+
var TypedObject = _TypedObject;
|
|
132
|
+
|
|
133
|
+
// src/utils/Emitter.ts
|
|
134
|
+
var import_node_events = require("events");
|
|
135
|
+
|
|
136
|
+
// src/Database.ts
|
|
137
|
+
var _Database = class _Database {
|
|
138
|
+
constructor(options) {
|
|
139
|
+
/**
|
|
140
|
+
* The low-level database driver handling basic operations.
|
|
141
|
+
*/
|
|
142
|
+
__publicField(this, "driver");
|
|
143
|
+
this.driver = options.driver;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Gets all the database contents from the cache.
|
|
147
|
+
*
|
|
148
|
+
* Type parameters:
|
|
149
|
+
*
|
|
150
|
+
* - `T` (`object`, defaults to `Record<string, any>`) - The type of object of all the database object to be returned.
|
|
151
|
+
*
|
|
152
|
+
* @returns {T} Cached database contents.
|
|
153
|
+
*
|
|
154
|
+
* @template T (object, defaults to `Record<string, any>`) -
|
|
155
|
+
* The type of object of all the database object to be returned.
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* const databaseContents = await database.all();
|
|
159
|
+
* console.log(databaseContents); // -> { ... (the object of all the data stored in database) }
|
|
160
|
+
*/
|
|
161
|
+
async all() {
|
|
162
|
+
const allDatabase = await this.driver.all();
|
|
163
|
+
return allDatabase;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Retrieves a value from database by a key.
|
|
167
|
+
*
|
|
168
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
169
|
+
* @returns {Maybe<ObjectValue<V, P>>} The value of the target in database.
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* const simpleValue = await database.get("simpleValue");
|
|
173
|
+
* console.log(simpleValue); // -> 123
|
|
174
|
+
*
|
|
175
|
+
* const databaseObjectPropertyAccessed = await database.get("youCanAlso.accessDatabaseObjectProperties.likeThat");
|
|
176
|
+
* console.log(databaseObjectPropertyAccessed); // -> "hello world!"
|
|
177
|
+
*
|
|
178
|
+
* // Assuming that the initial database object for this example is:
|
|
179
|
+
* // {
|
|
180
|
+
* // simpleValue: 123,
|
|
181
|
+
* // youCanAlso: {
|
|
182
|
+
* // accessDatabaseObjectProperties: {
|
|
183
|
+
* // likeThat: "hello world!"
|
|
184
|
+
* // }
|
|
185
|
+
* // }
|
|
186
|
+
* // }
|
|
187
|
+
*/
|
|
188
|
+
async get(key) {
|
|
189
|
+
if (key !== void 0) {
|
|
190
|
+
if (typeof key !== "string") {
|
|
191
|
+
throw new BlackCatError("INVALID_TYPE", "key", "string", typeOf(key));
|
|
192
|
+
}
|
|
193
|
+
return this.driver.get(key);
|
|
194
|
+
} else {
|
|
195
|
+
return this.all();
|
|
196
|
+
}
|
|
197
|
+
;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Retrieves a value from database by a key.
|
|
201
|
+
*
|
|
202
|
+
* - This method is an alias for {@link Database.get()} method.
|
|
203
|
+
*
|
|
204
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
205
|
+
* @returns {Maybe<ObjectValue<V, P>>} The value from database.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* const simpleValue = await database.fetch("simpleValue");
|
|
209
|
+
* console.log(simpleValue); // -> 123
|
|
210
|
+
*
|
|
211
|
+
* // You can use the dot notation to access the database object properties:
|
|
212
|
+
* const playerInventory = await database.fetch("player.inventory");
|
|
213
|
+
* console.log(playerInventory); // -> []
|
|
214
|
+
*
|
|
215
|
+
* // Assuming that the initial database object for this example is:
|
|
216
|
+
* // {
|
|
217
|
+
* // simpleValue: 123,
|
|
218
|
+
* // player: {
|
|
219
|
+
* // inventory: []
|
|
220
|
+
* // }
|
|
221
|
+
* // }
|
|
222
|
+
*/
|
|
223
|
+
async fetch(key) {
|
|
224
|
+
return this.get(key);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Determines if the data is stored in database.
|
|
228
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
229
|
+
* @returns {boolean} Whether the data is stored in database.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* const isSimpleValueInDatabase = await database.has("simpleValue");
|
|
233
|
+
* console.log(isSimpleValueInDatabase); // -> true
|
|
234
|
+
*
|
|
235
|
+
* const somethingElse = await database.has("somethingElse");
|
|
236
|
+
* console.log(somethingElse); // -> false
|
|
237
|
+
*
|
|
238
|
+
* // You can use the dot notation to check the database object properties:
|
|
239
|
+
* const isObjectInDatabase = await database.has("youCanAlso.accessObjectProperties.likeThat");
|
|
240
|
+
* console.log(isObjectInDatabase); // -> true
|
|
241
|
+
*
|
|
242
|
+
* // Assuming that the initial database object for this example is:
|
|
243
|
+
* // {
|
|
244
|
+
* // simpleValue: 123,
|
|
245
|
+
* // player: {
|
|
246
|
+
* // inventory: []
|
|
247
|
+
* // },
|
|
248
|
+
* // youCanAlso: {
|
|
249
|
+
* // accessObjectProperties: {
|
|
250
|
+
* // likeThat: "hello world!"
|
|
251
|
+
* // }
|
|
252
|
+
* // }
|
|
253
|
+
* // }
|
|
254
|
+
*/
|
|
255
|
+
async has(key) {
|
|
256
|
+
return this.get(key) !== null && this.get(key) !== void 0;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Writes the specified value into database under the specified key.
|
|
260
|
+
*
|
|
261
|
+
* @param {AutocompletableString<P>} key The key to write in the target.
|
|
262
|
+
* @param {ObjectValue<V, P>} value The value to write.
|
|
263
|
+
*
|
|
264
|
+
* @returns {Promise<If<IsObject<V>, FirstObjectKey<P>, V>>}
|
|
265
|
+
* - If the `value` parameter's type is not an object (string, number, boolean, etc), then the specified
|
|
266
|
+
* `value` parameter (type of `ObjectValue<V, P>`) will be returned.
|
|
267
|
+
*
|
|
268
|
+
* - If an object is specified in the `value` parameter, then the object of the first key will be returned.
|
|
269
|
+
* (type of `FirstObjectKey<P>` - first object key (e.g. in key `member.user.id`, the first key will be `member`))
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* // Assuming that the initial database object for this example is empty.
|
|
273
|
+
*
|
|
274
|
+
* await database.set("something", "hello");
|
|
275
|
+
* const hello = await database.get("something");
|
|
276
|
+
*
|
|
277
|
+
* console.log(hello); // -> "hello"
|
|
278
|
+
*
|
|
279
|
+
* // You can use the dot notation to write data in objects:
|
|
280
|
+
* const dotNotationSetResult = await database.set("member.user.id", 2000);
|
|
281
|
+
* console.log(dotNotationSetResult); // -> 2000
|
|
282
|
+
*
|
|
283
|
+
* await database.set("member.inventory", []);
|
|
284
|
+
* const inventory = await database.get("member.inventory");
|
|
285
|
+
*
|
|
286
|
+
* console.log(inventory); // -> []
|
|
287
|
+
*
|
|
288
|
+
* // Using objects as value will return the object of key `thats`:
|
|
289
|
+
* await database.set("member.user", { name: "Jerry" }); // -> { member: { user: { name: "Jerry" } } }
|
|
290
|
+
*
|
|
291
|
+
* // After these manipulations, the database object will look like this:
|
|
292
|
+
* // {
|
|
293
|
+
* // "something": "hello",
|
|
294
|
+
* // "member": {
|
|
295
|
+
* // "inventory": [],
|
|
296
|
+
* // "user": {
|
|
297
|
+
* // "name": "Jerry",
|
|
298
|
+
* // "id": 2000
|
|
299
|
+
* // }
|
|
300
|
+
* // }
|
|
301
|
+
* // }
|
|
302
|
+
*/
|
|
303
|
+
async set(key, value) {
|
|
304
|
+
const allDatabase = await this.all();
|
|
305
|
+
if (!key) {
|
|
306
|
+
throw new BlackCatError("REQUIRED_PARAMETER_MISSING", "key");
|
|
307
|
+
}
|
|
308
|
+
if (typeof key !== "string") {
|
|
309
|
+
throw new BlackCatError("INVALID_TYPE", "key", "string", typeOf(key));
|
|
310
|
+
}
|
|
311
|
+
const keys = key.split(".");
|
|
312
|
+
let currentObj = allDatabase;
|
|
313
|
+
for (let i = 0; i < keys.length; i++) {
|
|
314
|
+
if (keys.length - 1 === i) {
|
|
315
|
+
currentObj[keys[i]] = value;
|
|
316
|
+
} else {
|
|
317
|
+
if (!isObject(currentObj[keys[i]])) {
|
|
318
|
+
currentObj[keys[i]] = {};
|
|
319
|
+
}
|
|
320
|
+
currentObj = currentObj[keys[i]];
|
|
321
|
+
}
|
|
322
|
+
;
|
|
323
|
+
}
|
|
324
|
+
;
|
|
325
|
+
await this.driver.set(keys[0], allDatabase);
|
|
326
|
+
return typeof value == "object" && value !== null ? await this.get(keys[0]) : value;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Update the specified value into database under the specified key.
|
|
330
|
+
*
|
|
331
|
+
* @param {AutocompletableString<P>} key The key to update the target.
|
|
332
|
+
* @param {ObjectValue<V, P>} value The value to update.
|
|
333
|
+
*
|
|
334
|
+
* @returns {Promise<If<IsObject<V>, FirstObjectKey<P>, V>>}
|
|
335
|
+
* - If the `value` parameter's type is not an object (string, number, boolean, etc), then the specified
|
|
336
|
+
* `value` parameter (type of `ObjectValue<V, P>`) will be returned.
|
|
337
|
+
*
|
|
338
|
+
* - If an object is specified in the `value` parameter, then the object of the first key will be returned.
|
|
339
|
+
* (type of `FirstObjectKey<P>` - first object key (e.g. in key `member.user.id`, the first key will be `member`))
|
|
340
|
+
*/
|
|
341
|
+
async update(key, value) {
|
|
342
|
+
const allDatabase = await this.all();
|
|
343
|
+
const keys = key.split(".");
|
|
344
|
+
let current = allDatabase;
|
|
345
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
346
|
+
const part = keys[i];
|
|
347
|
+
if (!(part in current)) {
|
|
348
|
+
current[part] = {};
|
|
349
|
+
}
|
|
350
|
+
current = current[part];
|
|
351
|
+
}
|
|
352
|
+
const lastKey = keys[keys.length - 1];
|
|
353
|
+
current[lastKey] = value;
|
|
354
|
+
await this.driver.set(keys[0], allDatabase);
|
|
355
|
+
return current;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Performs an arithmetical addition on a target number in database.
|
|
359
|
+
*
|
|
360
|
+
* [!!!] The type of target value must be a number.
|
|
361
|
+
*
|
|
362
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
363
|
+
* @param {number} numberToAdd The number to add to the target number in database.
|
|
364
|
+
* @returns {Promise<number>} Addition operation result.
|
|
365
|
+
*
|
|
366
|
+
* @example
|
|
367
|
+
* const additionResult = await database.add("points", 5);
|
|
368
|
+
* console.log(additionResult); // -> 10 (5 + 5 = 10)
|
|
369
|
+
*
|
|
370
|
+
* // Notice that we don't need to assign a value to unexistent properties in database
|
|
371
|
+
* // before performing an addition since the initial target value is 0 and will be used
|
|
372
|
+
* // as the value of the unexistent property:
|
|
373
|
+
* const unexistentAdditionResult = await database.add("somethingElse", 3);
|
|
374
|
+
*
|
|
375
|
+
* console.log(unexistentAdditionResult); // -> 3 (0 + 3 = 3)
|
|
376
|
+
* // the property didn't exist in database, that's why 0 is added to 3
|
|
377
|
+
*
|
|
378
|
+
* // Assuming that the initial database object for this example is:
|
|
379
|
+
* // {
|
|
380
|
+
* // points: 5
|
|
381
|
+
* // }
|
|
382
|
+
*/
|
|
383
|
+
async add(key, numberToAdd) {
|
|
384
|
+
const targetNumber = await this.get(key) ?? 0;
|
|
385
|
+
if (!isNumber(targetNumber)) {
|
|
386
|
+
throw new BlackCatError("INVALID_TARGET", "number", typeOf(targetNumber));
|
|
387
|
+
}
|
|
388
|
+
if (numberToAdd === void 0) {
|
|
389
|
+
throw new BlackCatError("REQUIRED_PARAMETER_MISSING", "numberToAdd");
|
|
390
|
+
}
|
|
391
|
+
if (!isNumber(numberToAdd)) {
|
|
392
|
+
throw new BlackCatError("INVALID_TYPE", "numberToAdd", "number", typeOf(numberToAdd));
|
|
393
|
+
}
|
|
394
|
+
return await this.set(key, targetNumber + numberToAdd);
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Performs an arithmetical subtraction on a target number in database.
|
|
398
|
+
*
|
|
399
|
+
* [!!!] The type of target value must be a number.
|
|
400
|
+
*
|
|
401
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
402
|
+
* @param {number} numberToSubtract The number to subtract from the target number in database.
|
|
403
|
+
* @returns {Promise<number>} Subtraction operation result.
|
|
404
|
+
*
|
|
405
|
+
* @example
|
|
406
|
+
* const subtractionResult = await database.subtract("points", 5)
|
|
407
|
+
* console.log(subtractionResult) // -> 5 (10 - 5 = 5)
|
|
408
|
+
*
|
|
409
|
+
* // Notice that we don't need to assign a value to unexistent properties in database
|
|
410
|
+
* // before performing a subtraction since the initial target value is 0 and will be used
|
|
411
|
+
* // as the value of the unexistent property:
|
|
412
|
+
* const unexistentSubtractionitionResult = await database.subtract("somethingElse", 3)
|
|
413
|
+
*
|
|
414
|
+
* console.log(unexistentSubtractionitionResult) // -> 3 (0 - 3 = -3)
|
|
415
|
+
* // the property didn't exist in database, so 3 is subtracted from 0
|
|
416
|
+
*
|
|
417
|
+
* // Assuming that the initial database object for this example is:
|
|
418
|
+
* // {
|
|
419
|
+
* // points: 10
|
|
420
|
+
* // }
|
|
421
|
+
*/
|
|
422
|
+
async subtract(key, numberToSubtract) {
|
|
423
|
+
const targetNumber = await this.get(key) ?? 0;
|
|
424
|
+
if (!isNumber(targetNumber)) {
|
|
425
|
+
throw new BlackCatError("INVALID_TARGET", "number", typeOf(targetNumber));
|
|
426
|
+
}
|
|
427
|
+
if (numberToSubtract === void 0) {
|
|
428
|
+
throw new BlackCatError("REQUIRED_PARAMETER_MISSING", "numberToSubtract");
|
|
429
|
+
}
|
|
430
|
+
if (!isNumber(numberToSubtract)) {
|
|
431
|
+
throw new BlackCatError("INVALID_TYPE", "numberToSubtract", "number", typeOf(numberToSubtract));
|
|
432
|
+
}
|
|
433
|
+
return await this.set(key, targetNumber - numberToSubtract);
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Pushes the specified value(s) into the target array in database.
|
|
437
|
+
*
|
|
438
|
+
* [!!!] The type of target value must be an array.
|
|
439
|
+
* [!!!] get only values not stored in the database.
|
|
440
|
+
*
|
|
441
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
442
|
+
* @param {RestOrArray<ExtractFromArray<ObjectValue<V, P>>>} values
|
|
443
|
+
* The value(s) to be pushed into the target array in database.
|
|
444
|
+
*
|
|
445
|
+
* @returns {Promise<Array<ExtractFromArray<ObjectValue<V, P>>>>} Updated target array from database.
|
|
446
|
+
*
|
|
447
|
+
* @example
|
|
448
|
+
* console.log(await database.push("members", "Jerry")); // -> ["Tom", "Jerry"]
|
|
449
|
+
* // You can also pass in multiple values to push into the target array:
|
|
450
|
+
* console.log(await database.push("currencies", "VND")); // -> ["USD", "VND"]
|
|
451
|
+
*
|
|
452
|
+
* // Assuming that the initial database object for this example is:
|
|
453
|
+
* // {
|
|
454
|
+
* // members: ["Tom"],
|
|
455
|
+
* // currencies: ["USD"]
|
|
456
|
+
* // }
|
|
457
|
+
*/
|
|
458
|
+
async push(key, ...values) {
|
|
459
|
+
if (!values.length) {
|
|
460
|
+
throw new BlackCatError("REQUIRED_PARAMETER_MISSING", "values");
|
|
461
|
+
}
|
|
462
|
+
const root = await this.all();
|
|
463
|
+
const pathParts = key.split(".");
|
|
464
|
+
let target = root;
|
|
465
|
+
for (let i = 0; i < pathParts.length; i++) {
|
|
466
|
+
const part = pathParts[i];
|
|
467
|
+
if (!(part in target)) {
|
|
468
|
+
throw new BlackCatError("INVALID_KEY", key);
|
|
469
|
+
}
|
|
470
|
+
if (i === pathParts.length - 1) {
|
|
471
|
+
if (!Array.isArray(target[part])) {
|
|
472
|
+
throw new BlackCatError("INVALID_TARGET", "array", typeOf(target[part]));
|
|
473
|
+
}
|
|
474
|
+
const uniqueValues = values.filter((v) => !target[part].includes(v));
|
|
475
|
+
target[part].push(...uniqueValues);
|
|
476
|
+
} else {
|
|
477
|
+
target = target[part];
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
;
|
|
481
|
+
const topKey = pathParts[0];
|
|
482
|
+
await this.set(topKey, root[topKey]);
|
|
483
|
+
return target[pathParts[pathParts.length - 1]];
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Replaces the specified element in target array with the specified value in the target array in database.
|
|
487
|
+
*
|
|
488
|
+
* [!!!] The type of target value must be an array.
|
|
489
|
+
*
|
|
490
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
491
|
+
* @param {number} targetArrayElementIndex The index to find the element in target array by.
|
|
492
|
+
* @param {V} value The value to be pushed into the target array in database.
|
|
493
|
+
* @returns {Promise<Array<ExtractFromArray<ObjectValue<V, P>>>>} Updated target array from database.
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* console.log(await database.pull("members", 1, "James")); // -> ["Jerry", "James", "Tom"]
|
|
497
|
+
*
|
|
498
|
+
* // Assuming that the initial database object for this example is:
|
|
499
|
+
* // {
|
|
500
|
+
* // members: ["Jerry", "William", "Tom"]
|
|
501
|
+
* // }
|
|
502
|
+
*/
|
|
503
|
+
async pull(key, targetArrayElementIndex, value) {
|
|
504
|
+
if (!isNumber(targetArrayElementIndex)) {
|
|
505
|
+
throw new BlackCatError("INVALID_TYPE", "targetArrayElementIndex", "number", typeOf(targetArrayElementIndex));
|
|
506
|
+
}
|
|
507
|
+
;
|
|
508
|
+
if (value === void 0) {
|
|
509
|
+
throw new BlackCatError("REQUIRED_PARAMETER_MISSING", "value");
|
|
510
|
+
}
|
|
511
|
+
;
|
|
512
|
+
const root = await this.all();
|
|
513
|
+
const pathParts = key.split(".");
|
|
514
|
+
let target = root;
|
|
515
|
+
for (let i = 0; i < pathParts.length; i++) {
|
|
516
|
+
const part = pathParts[i];
|
|
517
|
+
if (!(part in target)) {
|
|
518
|
+
throw new BlackCatError("INVALID_KEY", `Path "${key}" does not exist`);
|
|
519
|
+
}
|
|
520
|
+
if (i === pathParts.length - 1) {
|
|
521
|
+
if (!Array.isArray(target[part])) {
|
|
522
|
+
throw new BlackCatError("INVALID_TARGET", "array", typeOf(target[part]));
|
|
523
|
+
}
|
|
524
|
+
;
|
|
525
|
+
const arr = target[part];
|
|
526
|
+
const index = targetArrayElementIndex >= 0 ? targetArrayElementIndex : arr.length + targetArrayElementIndex;
|
|
527
|
+
if (index < 0 || index >= arr.length) {
|
|
528
|
+
console.error(`Index ${targetArrayElementIndex} is out of bounds`);
|
|
529
|
+
}
|
|
530
|
+
;
|
|
531
|
+
arr[index] = value;
|
|
532
|
+
} else {
|
|
533
|
+
target = target[part];
|
|
534
|
+
}
|
|
535
|
+
;
|
|
536
|
+
}
|
|
537
|
+
;
|
|
538
|
+
await this.set(pathParts[0], root[pathParts[0]]);
|
|
539
|
+
return target[pathParts[pathParts.length - 1]];
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Removes the specified element(s) from the target array in database.
|
|
543
|
+
*
|
|
544
|
+
* [!!!] The type of target value must be an array.
|
|
545
|
+
*
|
|
546
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
547
|
+
* @param {RestOrArray<ExtractFromArray<number>>} targetArrayElementIndexes
|
|
548
|
+
* The index(es) to find the element(s) in target array by.
|
|
549
|
+
*
|
|
550
|
+
* @returns {Promise<Array<ExtractFromArray<ObjectValue<V, P>>>>} Updated target array from database.
|
|
551
|
+
*
|
|
552
|
+
* @example
|
|
553
|
+
* console.log(await database.pop("members", 1)); // -> ["Jerry", "Tom"]
|
|
554
|
+
*
|
|
555
|
+
* console.log(await database.pop("currencies", 1)); // -> ["VND", "Euro"]
|
|
556
|
+
*
|
|
557
|
+
* // Assuming that the initial database object for this example is:
|
|
558
|
+
* // {
|
|
559
|
+
* // members: ["Jerry", "William", "Tom"],
|
|
560
|
+
* // currencies: ["VND", "USD", "Euro"]
|
|
561
|
+
* // }
|
|
562
|
+
*/
|
|
563
|
+
async pop(key, ...targetArrayElementIndexes) {
|
|
564
|
+
const targetArray = await this.get(key) ?? [];
|
|
565
|
+
if (!Array.isArray(targetArray)) {
|
|
566
|
+
throw new BlackCatError("INVALID_TARGET", "array", typeOf(targetArray));
|
|
567
|
+
}
|
|
568
|
+
;
|
|
569
|
+
if (!targetArrayElementIndexes.length) {
|
|
570
|
+
throw new BlackCatError("REQUIRED_PARAMETER_MISSING", "targetArrayElementIndex");
|
|
571
|
+
}
|
|
572
|
+
;
|
|
573
|
+
const indexes = Array.isArray(targetArrayElementIndexes[0]) ? targetArrayElementIndexes[0] : targetArrayElementIndexes;
|
|
574
|
+
if (indexes.some((index) => !isNumber(index))) {
|
|
575
|
+
throw new BlackCatError("ONE_OR_MORE_ARRAY_TYPES_INVALID", "targetArrayElementIndexes", "number", createTypesArray(indexes));
|
|
576
|
+
}
|
|
577
|
+
;
|
|
578
|
+
const sortedIndexes = [...indexes].sort((a, b) => b - a);
|
|
579
|
+
const removedElements = [];
|
|
580
|
+
for (const index of sortedIndexes) {
|
|
581
|
+
const removed = targetArray.splice(index, 1);
|
|
582
|
+
removedElements.push(...removed);
|
|
583
|
+
}
|
|
584
|
+
;
|
|
585
|
+
const parentPath = key.split(".").slice(0, -1).join(".");
|
|
586
|
+
const fieldName = key.split(".").slice(-1)[0];
|
|
587
|
+
if (parentPath) {
|
|
588
|
+
const parentObject = await this.get(parentPath) ?? {};
|
|
589
|
+
parentObject[fieldName] = targetArray;
|
|
590
|
+
await this.set(parentPath, parentObject);
|
|
591
|
+
} else {
|
|
592
|
+
await this.set(key, targetArray);
|
|
593
|
+
}
|
|
594
|
+
;
|
|
595
|
+
return removedElements;
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Determines whether the specified target is an array.
|
|
599
|
+
*
|
|
600
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
601
|
+
* @returns {Promise<boolean>} Whether the target is an array.
|
|
602
|
+
*
|
|
603
|
+
* @example
|
|
604
|
+
* console.log(await databse.isTargetArray("array")); // => true
|
|
605
|
+
* console.log(await databse.isTargetArray("notArray")); // => false
|
|
606
|
+
*
|
|
607
|
+
* // Assuming that the initial database object for this example is:
|
|
608
|
+
* // {
|
|
609
|
+
* // array: [],
|
|
610
|
+
* // notArray: 123
|
|
611
|
+
* // }
|
|
612
|
+
*/
|
|
613
|
+
async isTargetArray(key) {
|
|
614
|
+
const target = await this.get(key);
|
|
615
|
+
return Array.isArray(target);
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Determines whether the specified target is a number.
|
|
619
|
+
*
|
|
620
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
621
|
+
* @returns {Promise<boolean>} Whether the target is a number.
|
|
622
|
+
*
|
|
623
|
+
* @example
|
|
624
|
+
* console.log(await database.isTargetNumber("number")); // -> true
|
|
625
|
+
* console.log(await database.isTargetNumber("notNumber")); // -> false
|
|
626
|
+
*
|
|
627
|
+
* // Assuming that the initial database object for this example is:
|
|
628
|
+
* // {
|
|
629
|
+
* // number: 123,
|
|
630
|
+
* // notNumber: []
|
|
631
|
+
* // }
|
|
632
|
+
*/
|
|
633
|
+
async isTargetNumber(key) {
|
|
634
|
+
const target = await this.get(key);
|
|
635
|
+
return isNumber(target);
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Returns an array of object keys by specified database key.
|
|
639
|
+
*
|
|
640
|
+
* If `key` parameter is omitted, then an array of object keys of database root object will be returned.
|
|
641
|
+
*
|
|
642
|
+
* Type parameters:
|
|
643
|
+
*
|
|
644
|
+
* - `TKeys` (`TupleOrArray<string>`, defaults to `K[]`) - The tuple or array of a type of keys to be returned.
|
|
645
|
+
*
|
|
646
|
+
* @param {P} [key] The key to access the target in database by.
|
|
647
|
+
* @returns {Array<ObjectPath<P>>} Database object keys array.
|
|
648
|
+
*
|
|
649
|
+
* @example
|
|
650
|
+
* const prop3Keys = await database.keys("prop3");
|
|
651
|
+
* console.log(prop3Keys) // -> ["prop4", "prop5"]
|
|
652
|
+
*
|
|
653
|
+
* const prop5Keys = await database.keys("prop3.prop5");
|
|
654
|
+
* console.log(prop5Keys) // -> ["prop6"]
|
|
655
|
+
*
|
|
656
|
+
* const prop6Keys = await database.keys("prop3.prop5.prop6");
|
|
657
|
+
* console.log(prop6Keys)
|
|
658
|
+
* // -> [] (empty since the value in `prop6`, 111, is a primitive value and not an actual object)
|
|
659
|
+
*
|
|
660
|
+
* const databaseKeys = await database.keys();
|
|
661
|
+
* // in this example, `key` parameter is omitted - object keys of database object are being returned
|
|
662
|
+
*
|
|
663
|
+
* console.log(databaseKeys) // -> ["prop1", "prop2", "prop3"]
|
|
664
|
+
*
|
|
665
|
+
* const unexistentKeys = await database.keys("somethingElse");
|
|
666
|
+
* console.log(unexistentKeys) // -> [] (empty since the key `somethingElse` does not exist in database)
|
|
667
|
+
*
|
|
668
|
+
* // Assuming that the initial database object for this example is:
|
|
669
|
+
* // {
|
|
670
|
+
* // prop1: 123,
|
|
671
|
+
* // prop2: 456,
|
|
672
|
+
* // prop3: {
|
|
673
|
+
* // prop4: 789,
|
|
674
|
+
* // prop5: {
|
|
675
|
+
* // prop6: 111
|
|
676
|
+
* // }
|
|
677
|
+
* // }
|
|
678
|
+
* // }
|
|
679
|
+
*/
|
|
680
|
+
async keys(key) {
|
|
681
|
+
if (!key) return TypedObject.keys(await this.all());
|
|
682
|
+
const data = await this.get(key);
|
|
683
|
+
return TypedObject.keys(data).filter((key2) => data[key2] !== void 0 && data[key2] !== null);
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Determines the number of keys in the root of the database.
|
|
687
|
+
* @type {Promise<number>} amount of data.
|
|
688
|
+
*/
|
|
689
|
+
async size() {
|
|
690
|
+
const keys = await this.keys();
|
|
691
|
+
return keys.length;
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Returns an array of object values by specified database key.
|
|
695
|
+
*
|
|
696
|
+
* If `key` parameter is omitted, then an array of object values of database root object will be returned.
|
|
697
|
+
*
|
|
698
|
+
* @param {P} [key] The key to access the target in database by.
|
|
699
|
+
* @returns {Array<ObjectValue<V, P>>} Database object values array.
|
|
700
|
+
*
|
|
701
|
+
* @example
|
|
702
|
+
* const prop3Values = await database.values("prop3");
|
|
703
|
+
* console.log(prop3Values); // -> [789, { prop6: 111 }]
|
|
704
|
+
*
|
|
705
|
+
* const prop5Values = await database.values("prop3.prop5");
|
|
706
|
+
* console.log(prop5Values); // -> []
|
|
707
|
+
*
|
|
708
|
+
* const prop6Values = await database.values("prop3.prop5.prop6");
|
|
709
|
+
* console.log(prop6Values);
|
|
710
|
+
* // -> [] (empty since the value in `prop6`, 111, is a primitive value and not an actual object)
|
|
711
|
+
*
|
|
712
|
+
* const databaseValues = await database.values();
|
|
713
|
+
* // in this example, `key` parameter is omitted - object values of database object are being returned
|
|
714
|
+
*
|
|
715
|
+
* console.log(databaseValues); // -> [123, 456, { prop4: 789, prop5: { prop6: 111 } }]
|
|
716
|
+
*
|
|
717
|
+
* const unexistentValues = await database.values("somethingElse");
|
|
718
|
+
* console.log(unexistentValues); // -> [] (empty since the key `somethingElse` does not exist in database)
|
|
719
|
+
*
|
|
720
|
+
* // Assuming that the initial database object for this example is:
|
|
721
|
+
* // {
|
|
722
|
+
* // prop1: 123,
|
|
723
|
+
* // prop2: 456,
|
|
724
|
+
* // prop3: {
|
|
725
|
+
* // prop4: 789,
|
|
726
|
+
* // prop5: {
|
|
727
|
+
* // prop6: 111
|
|
728
|
+
* // }
|
|
729
|
+
* // }
|
|
730
|
+
* // }
|
|
731
|
+
*/
|
|
732
|
+
async values(key) {
|
|
733
|
+
if (!key) return TypedObject.values(await this.all());
|
|
734
|
+
const data = await this.get(key);
|
|
735
|
+
return TypedObject.values(data);
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* This method works the same way as `Array.find()`.
|
|
739
|
+
*
|
|
740
|
+
* Iterates over root database values, finds the element in database values array
|
|
741
|
+
* by specified condition in the callback function and returns the result.
|
|
742
|
+
*
|
|
743
|
+
* @param {QueryFunction<V>} queryFunction
|
|
744
|
+
* A function that accepts up to three arguments.
|
|
745
|
+
* The `find` method calls the `queryFunction` once for each element in database object values array.
|
|
746
|
+
*
|
|
747
|
+
* @returns {Promise<Maybe<V>>} The search
|
|
748
|
+
*/
|
|
749
|
+
async find(queryFunction) {
|
|
750
|
+
const values = await this.values();
|
|
751
|
+
return values.find(queryFunction) ?? null;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* This method works the same way as `Array.map()`.
|
|
755
|
+
*
|
|
756
|
+
* Calls a defined callback function on each element of an array,
|
|
757
|
+
* and returns an array that contains the results.
|
|
758
|
+
*
|
|
759
|
+
* @param {QueryFunction<V, TReturnType>} queryFunction
|
|
760
|
+
* A function that accepts up to three arguments.
|
|
761
|
+
* The `map` method calls the `queryFunction` once for each element in database object values array.
|
|
762
|
+
*
|
|
763
|
+
* @returns {Promise<TReturnType[]>}
|
|
764
|
+
*/
|
|
765
|
+
async map(queryFunction) {
|
|
766
|
+
const values = await this.values();
|
|
767
|
+
return values.map(queryFunction);
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* This method works the same way as `Array.findIndex()`.
|
|
771
|
+
*
|
|
772
|
+
* Iterates over root database values, finds the index of the element in database values array
|
|
773
|
+
* by specified condition in the callback function and returns the result.
|
|
774
|
+
*
|
|
775
|
+
* @param {QueryFunction<V>} queryFunction
|
|
776
|
+
* A function that accepts up to three arguments.
|
|
777
|
+
* The `findIndex` method calls the `queryFunction` once for each element in database object values array.
|
|
778
|
+
*
|
|
779
|
+
* @returns {Promise<number>}
|
|
780
|
+
*/
|
|
781
|
+
async findIndex(queryFunction) {
|
|
782
|
+
const values = await this.values();
|
|
783
|
+
return values.findIndex(queryFunction);
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* This method works the same way as `Array.filter()`.
|
|
787
|
+
*
|
|
788
|
+
* Iterates over root database values, finds all the element that match the
|
|
789
|
+
* specified condition in the callback function and returns the result.
|
|
790
|
+
*
|
|
791
|
+
* @param {QueryFunction<V>} queryFunction
|
|
792
|
+
* A function that accepts up to three arguments.
|
|
793
|
+
* The `filter` method calls the `queryFunction` once for each element in database object values array.
|
|
794
|
+
*
|
|
795
|
+
* @returns {Promise<V[]>}
|
|
796
|
+
*/
|
|
797
|
+
async filter(queryFunction) {
|
|
798
|
+
const values = await this.values();
|
|
799
|
+
return values.filter(queryFunction);
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* This method works the same way as `Array.some()`.
|
|
803
|
+
*
|
|
804
|
+
* Iterates over root database values and checks if the
|
|
805
|
+
* specified condition in the callback function returns `true`
|
|
806
|
+
* for **any** of the elements of the database object values array.
|
|
807
|
+
*
|
|
808
|
+
* @param {QueryFunction<V>} queryFunction
|
|
809
|
+
* A function that accepts up to three arguments.
|
|
810
|
+
* The `some` method calls the `queryFunction` once for each element in database object values array.
|
|
811
|
+
*
|
|
812
|
+
* @returns {Promise<boolean>}
|
|
813
|
+
*/
|
|
814
|
+
async some(queryFunction) {
|
|
815
|
+
const values = await this.values();
|
|
816
|
+
return values.some(queryFunction);
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* This method works the same way as `Array.every()`.
|
|
820
|
+
*
|
|
821
|
+
* Iterates over root database values and checks if the
|
|
822
|
+
* specified condition in the callback function returns `true`
|
|
823
|
+
* for **all** of the elements of the database object values array.
|
|
824
|
+
*
|
|
825
|
+
* @param {QueryFunction<V>} queryFunction
|
|
826
|
+
* A function that accepts up to three arguments.
|
|
827
|
+
* The `every` method calls the `queryFunction` once for each element in database object values array.
|
|
828
|
+
*
|
|
829
|
+
* @returns {Promise<boolean>}
|
|
830
|
+
*/
|
|
831
|
+
async every(queryFunction) {
|
|
832
|
+
const values = await this.values();
|
|
833
|
+
return values.every(queryFunction);
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Picks a random element of array in database and returns the picked array element.
|
|
837
|
+
*
|
|
838
|
+
* [!!!] The type of target value must be an array.
|
|
839
|
+
*
|
|
840
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
841
|
+
* @returns {Promise<Maybe<ObjectValue<V, P>>>} The randomly picked element in the database array.
|
|
842
|
+
*
|
|
843
|
+
* @example
|
|
844
|
+
* const array = await database.get("array"); // assuming that the array is ['example1', 'example2', 'example3']
|
|
845
|
+
* console.log(array); // -> ['example1', 'example2', 'example3']
|
|
846
|
+
*
|
|
847
|
+
* const randomArrayElement = await database.random("exampleArray");
|
|
848
|
+
* console.log(randomArrayElement); // -> randomly picked array element: either 'example1', 'example2', or 'example3'
|
|
849
|
+
*/
|
|
850
|
+
async random(key) {
|
|
851
|
+
const array = await this.get(key);
|
|
852
|
+
if (!Array.isArray(array)) {
|
|
853
|
+
throw new BlackCatError("INVALID_TARGET", "array", typeOf(array));
|
|
854
|
+
}
|
|
855
|
+
return array[Math.floor(Math.random() * array.length)] ?? null;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Deletes the data from database by key.
|
|
859
|
+
* @param {AutocompletableString<P>} key The key to access the target in database by.
|
|
860
|
+
* @returns {Promise<boolean>} Whether the deletion was successful.
|
|
861
|
+
*/
|
|
862
|
+
async delete(key) {
|
|
863
|
+
if (typeof key !== "string") {
|
|
864
|
+
throw new BlackCatError("INVALID_TYPE", "key", "string", typeof key);
|
|
865
|
+
}
|
|
866
|
+
;
|
|
867
|
+
const allDatabase = await this.all();
|
|
868
|
+
const keys = key.split(".");
|
|
869
|
+
const lastKey = keys.pop();
|
|
870
|
+
let currentObj = allDatabase;
|
|
871
|
+
for (const k of keys) {
|
|
872
|
+
if (!isObject(currentObj[k])) {
|
|
873
|
+
return false;
|
|
874
|
+
}
|
|
875
|
+
currentObj = currentObj[k];
|
|
876
|
+
}
|
|
877
|
+
if (!(lastKey in currentObj)) return false;
|
|
878
|
+
delete currentObj[lastKey];
|
|
879
|
+
await this.driver.delete(allDatabase);
|
|
880
|
+
return true;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Deletes everything from the database.
|
|
884
|
+
*
|
|
885
|
+
* - This method is an alias for {@link QuickMongo.clear()} method.
|
|
886
|
+
* @returns {Promise<boolean>} `true` if cleared successfully, `false` otherwise.
|
|
887
|
+
*/
|
|
888
|
+
async deleteAll() {
|
|
889
|
+
await this.driver.delete();
|
|
890
|
+
return true;
|
|
891
|
+
}
|
|
892
|
+
};
|
|
893
|
+
__name(_Database, "Database");
|
|
894
|
+
var Database = _Database;
|
|
895
|
+
|
|
896
|
+
// src/drivers/JSONDriver.ts
|
|
897
|
+
var import_fs = require("fs");
|
|
898
|
+
var _JSONDriver = class _JSONDriver {
|
|
899
|
+
/**
|
|
900
|
+
* JSONDriver class.
|
|
901
|
+
* @param options.filePath Json database file path.
|
|
902
|
+
* @param options.minifyJSON Minifies the JSON content in database file to save some space.
|
|
903
|
+
*/
|
|
904
|
+
constructor(options) {
|
|
905
|
+
/**
|
|
906
|
+
* JSON database file path.
|
|
907
|
+
* @type {string}
|
|
908
|
+
*/
|
|
909
|
+
__publicField(this, "filePath");
|
|
910
|
+
/**
|
|
911
|
+
* Minifies the JSON content in database file to save some space.
|
|
912
|
+
* @type {boolean}
|
|
913
|
+
*/
|
|
914
|
+
__publicField(this, "minifyJSON");
|
|
915
|
+
this.filePath = options.filePath || "database.json";
|
|
916
|
+
this.minifyJSON = options.minifyJSON || false;
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Returns all data from JSON database.
|
|
920
|
+
*
|
|
921
|
+
* @returns {Promise<any>} All data from JSON database.
|
|
922
|
+
*
|
|
923
|
+
* @template V The type of data being returned.
|
|
924
|
+
*/
|
|
925
|
+
async all() {
|
|
926
|
+
return import_fs.promises.readFile(this.filePath, "utf-8").then((content) => JSON.parse(content)).catch((error) => {
|
|
927
|
+
console.error(`Failed to load database file: ${this.filePath}`, error);
|
|
928
|
+
return {};
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Parses the key and fetches the value from JSON database.
|
|
933
|
+
*
|
|
934
|
+
* Type parameters:
|
|
935
|
+
*
|
|
936
|
+
* - `V` - The type of data being returned.
|
|
937
|
+
*
|
|
938
|
+
* @param {string} key The key in JSON database.
|
|
939
|
+
* @returns {Promise<V>} The data from JSON database.
|
|
940
|
+
*
|
|
941
|
+
* @template V The type of data being returned.
|
|
942
|
+
*/
|
|
943
|
+
async get(key) {
|
|
944
|
+
const data = await this.all();
|
|
945
|
+
const keys = key.split(".");
|
|
946
|
+
let result = data;
|
|
947
|
+
for (const k of keys) {
|
|
948
|
+
if (result === null || typeof result !== "object") return null;
|
|
949
|
+
result = result[k];
|
|
950
|
+
}
|
|
951
|
+
return result;
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Parses the key and sets the value in JSON database.
|
|
955
|
+
*
|
|
956
|
+
* Type parameters:
|
|
957
|
+
*
|
|
958
|
+
* - `V` - The type of data being set.
|
|
959
|
+
* - `R` - The type of data being returned.
|
|
960
|
+
*
|
|
961
|
+
* @param {string} key The key in JSON database.
|
|
962
|
+
* @returns {Promise<R>} The data from JSON database.
|
|
963
|
+
*
|
|
964
|
+
* @template V The type of data being set.
|
|
965
|
+
* @template R The type of data being returned.
|
|
966
|
+
*/
|
|
967
|
+
async set(key, value) {
|
|
968
|
+
const data = await this.all();
|
|
969
|
+
await import_fs.promises.writeFile(this.filePath, JSON.stringify(value, null, this.minifyJSON ? void 0 : " "));
|
|
970
|
+
return data;
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Parses the key and deletes it from JSON database. If no key is provided, clears the database.
|
|
974
|
+
* @param {V} key The key in JSON database.
|
|
975
|
+
* @returns {Promise<boolean>} `true` if deleted successfully.
|
|
976
|
+
*/
|
|
977
|
+
async delete(key) {
|
|
978
|
+
if (key === void 0) {
|
|
979
|
+
await import_fs.promises.writeFile(this.filePath, "{}");
|
|
980
|
+
return true;
|
|
981
|
+
} else {
|
|
982
|
+
await import_fs.promises.writeFile(this.filePath, JSON.stringify(key, null, this.minifyJSON ? void 0 : " "));
|
|
983
|
+
}
|
|
984
|
+
;
|
|
985
|
+
return true;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
__name(_JSONDriver, "JSONDriver");
|
|
989
|
+
var JSONDriver = _JSONDriver;
|
|
990
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
991
|
+
0 && (module.exports = {
|
|
992
|
+
Database,
|
|
993
|
+
JSONDriver
|
|
994
|
+
});
|
|
995
|
+
//# sourceMappingURL=index.js.map
|