@wxn0brp/db 0.0.8 → 0.1.0

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.
Files changed (55) hide show
  1. package/dist/cjs/CollectionManager.d.ts +1 -1
  2. package/dist/cjs/CollectionManager.js +2 -2
  3. package/dist/cjs/action.d.ts +1 -1
  4. package/dist/cjs/action.js +11 -11
  5. package/dist/cjs/client/database.d.ts +4 -4
  6. package/dist/cjs/client/database.js +29 -55
  7. package/dist/cjs/client/graph.d.ts +2 -2
  8. package/dist/cjs/client/graph.js +22 -21
  9. package/dist/cjs/client/remote.d.ts +1 -2
  10. package/dist/cjs/database.js +6 -6
  11. package/dist/cjs/file/find.js +11 -11
  12. package/dist/cjs/file/index.js +4 -4
  13. package/dist/cjs/file/remove.js +7 -7
  14. package/dist/cjs/file/update.js +10 -10
  15. package/dist/cjs/format.d.ts +1 -7
  16. package/dist/cjs/format.js +0 -6
  17. package/dist/cjs/gen.d.ts +6 -3
  18. package/dist/cjs/gen.js +111 -52
  19. package/dist/cjs/graph.js +2 -2
  20. package/dist/cjs/index.js +12 -12
  21. package/dist/cjs/relation.d.ts +17 -47
  22. package/dist/cjs/relation.js +31 -34
  23. package/dist/cjs/types/arg.d.ts +4 -4
  24. package/dist/cjs/types/searchOpts.d.ts +1 -1
  25. package/dist/cjs/utils/hasFields.d.ts +4 -5
  26. package/dist/cjs/utils/hasFields.js +3 -4
  27. package/dist/cjs/utils/hasFieldsAdvanced.d.ts +1 -1
  28. package/dist/cjs/utils/hasFieldsAdvanced.js +3 -3
  29. package/dist/cjs/utils/updateFindObject.d.ts +8 -8
  30. package/dist/cjs/utils/updateFindObject.js +6 -7
  31. package/dist/cjs/utils/updateObject.d.ts +1 -1
  32. package/dist/esm/CollectionManager.d.ts +1 -1
  33. package/dist/esm/CollectionManager.js +2 -2
  34. package/dist/esm/action.d.ts +1 -1
  35. package/dist/esm/action.js +1 -1
  36. package/dist/esm/client/database.d.ts +4 -4
  37. package/dist/esm/client/database.js +26 -52
  38. package/dist/esm/client/graph.d.ts +2 -2
  39. package/dist/esm/client/graph.js +22 -21
  40. package/dist/esm/client/remote.d.ts +1 -2
  41. package/dist/esm/format.d.ts +1 -7
  42. package/dist/esm/format.js +0 -6
  43. package/dist/esm/gen.d.ts +6 -3
  44. package/dist/esm/gen.js +111 -52
  45. package/dist/esm/relation.d.ts +17 -47
  46. package/dist/esm/relation.js +31 -34
  47. package/dist/esm/types/arg.d.ts +4 -4
  48. package/dist/esm/types/searchOpts.d.ts +1 -1
  49. package/dist/esm/utils/hasFields.d.ts +4 -5
  50. package/dist/esm/utils/hasFields.js +3 -4
  51. package/dist/esm/utils/hasFieldsAdvanced.d.ts +1 -1
  52. package/dist/esm/utils/updateFindObject.d.ts +8 -8
  53. package/dist/esm/utils/updateFindObject.js +6 -7
  54. package/dist/esm/utils/updateObject.d.ts +1 -1
  55. package/package.json +5 -5
@@ -1,8 +1,8 @@
1
1
  import CollectionManager from "../CollectionManager.js";
2
- import { Remote, RequestData } from "./remote.js";
3
- import { Arg, Search, Updater } from "../types/arg";
2
+ import { Remote } from "./remote.js";
3
+ import { Arg, Search, Updater } from "../types/arg.js";
4
4
  import { DbFindOpts, FindOpts } from "../types/options.js";
5
- import { Context } from "../types/types";
5
+ import { Context } from "../types/types.js";
6
6
  import Data from "../types/data.js";
7
7
  /**
8
8
  * Represents a database management class for performing CRUD operations.
@@ -15,7 +15,7 @@ declare class DataBaseRemote {
15
15
  /**
16
16
  * Make a request to the remote database.
17
17
  */
18
- _request<T>(type: string, data: RequestData): Promise<T>;
18
+ _request<T>(type: string, params?: any[]): Promise<T>;
19
19
  /**
20
20
  * Create a new instance of a CollectionManager class.
21
21
  */
@@ -1,4 +1,4 @@
1
- import got from "got";
1
+ import ky from "ky";
2
2
  import CollectionManager from "../CollectionManager.js";
3
3
  import serializeFunctions from "./function.js";
4
4
  /**
@@ -14,25 +14,23 @@ class DataBaseRemote {
14
14
  /**
15
15
  * Make a request to the remote database.
16
16
  */
17
- async _request(type, data) {
18
- data.db = this.remote.name;
19
- const processed = serializeFunctions(data);
20
- data = {
21
- keys: processed.keys,
22
- ...processed.data
17
+ async _request(type, params = []) {
18
+ const processed = serializeFunctions(params);
19
+ const data = {
20
+ db: this.remote.name,
21
+ params: processed.data,
22
+ keys: processed.keys
23
23
  };
24
- const res = await got.post(this.remote.url + "/db/database/" + type, {
25
- // @ts-ignore: Some jerk can't do the types correctly.
26
- body: data,
24
+ const res = await ky.post(this.remote.url + "/db/" + type, {
25
+ json: data,
27
26
  headers: {
28
27
  "Authorization": this.remote.auth
29
28
  },
30
- json: true,
31
- responseType: "json"
32
- });
33
- if (res.body.err)
34
- throw new Error(res.body.msg);
35
- return res.body.result;
29
+ throwHttpErrors: false
30
+ }).json();
31
+ if (res.err)
32
+ throw new Error(res.msg);
33
+ return res.result;
36
34
  }
37
35
  /**
38
36
  * Create a new instance of a CollectionManager class.
@@ -44,97 +42,73 @@ class DataBaseRemote {
44
42
  * Get the names of all available databases.
45
43
  */
46
44
  async getCollections() {
47
- return await this._request("getCollections", {});
45
+ return await this._request("getCollections", []);
48
46
  }
49
47
  /**
50
48
  * Check and create the specified collection if it doesn't exist.
51
49
  */
52
50
  async checkCollection(collection) {
53
- return await this._request("checkCollection", { collection });
51
+ return await this._request("checkCollection", [collection]);
54
52
  }
55
53
  /**
56
54
  * Check if a collection exists.
57
55
  */
58
56
  async issetCollection(collection) {
59
- return await this._request("issetCollection", { collection });
57
+ return await this._request("issetCollection", [collection]);
60
58
  }
61
59
  /**
62
60
  * Add data to a database.
63
61
  */
64
62
  async add(collection, data, id_gen = true) {
65
- return await this._request("add", { collection, data, id_gen });
63
+ return await this._request("add", [collection, data, id_gen]);
66
64
  }
67
65
  /**
68
66
  * Find data in a database.
69
67
  */
70
68
  async find(collection, search, context = {}, options = {}, findOpts = {}) {
71
- const searchStr = typeof search === "function" ? search.toString() : search;
72
- const findOptsRemote = {};
73
- if (findOpts.select)
74
- findOptsRemote.select = findOpts.select;
75
- if (findOpts.exclude)
76
- findOptsRemote.exclude = findOpts.exclude;
77
- if (findOpts.transform)
78
- findOptsRemote.transform = findOpts.transform.toString();
79
- return await this._request("find", { collection, search: searchStr, options, context, findOpts });
69
+ return await this._request("find", [collection, search, context, options, findOpts]);
80
70
  }
81
71
  /**
82
72
  * Find one data entry in a database.
83
73
  */
84
74
  async findOne(collection, search, context = {}, findOpts = {}) {
85
- const searchStr = typeof search === "function" ? search.toString() : search;
86
- const findOptsRemote = {};
87
- if (findOpts.select)
88
- findOptsRemote.select = findOpts.select;
89
- if (findOpts.exclude)
90
- findOptsRemote.exclude = findOpts.exclude;
91
- if (findOpts.transform)
92
- findOptsRemote.transform = findOpts.transform.toString();
93
- return await this._request("findOne", { collection, search: searchStr, context, findOpts });
75
+ return await this._request("findOne", [collection, search, context, findOpts]);
94
76
  }
95
77
  /**
96
78
  * Update data in a database.
97
79
  */
98
80
  async update(collection, search, updater, context = {}) {
99
- const searchStr = typeof search === "function" ? search.toString() : search;
100
- const argStr = typeof updater === "function" ? updater.toString() : updater;
101
- return await this._request("update", { collection, search: searchStr, arg: argStr, context });
81
+ return await this._request("update", [collection, search, updater, context]);
102
82
  }
103
83
  /**
104
84
  * Update one data entry in a database.
105
85
  */
106
86
  async updateOne(collection, search, updater, context = {}) {
107
- const searchStr = typeof search === "function" ? search.toString() : search;
108
- const argStr = typeof updater === "function" ? updater.toString() : updater;
109
- return await this._request("updateOne", { collection, search: searchStr, arg: argStr, context });
87
+ return await this._request("updateOne", [collection, search, updater, context]);
110
88
  }
111
89
  /**
112
90
  * Remove data from a database.
113
91
  */
114
92
  async remove(collection, search, context = {}) {
115
- const searchStr = typeof search === "function" ? search.toString() : search;
116
- return await this._request("remove", { collection, search: searchStr, context });
93
+ return await this._request("remove", [collection, search, context]);
117
94
  }
118
95
  /**
119
96
  * Remove one data entry from a database.
120
97
  */
121
98
  async removeOne(collection, search, context = {}) {
122
- const searchStr = typeof search === "function" ? search.toString() : search;
123
- return await this._request("removeOne", { collection, search: searchStr, context });
99
+ return await this._request("removeOne", [collection, search, context]);
124
100
  }
125
101
  /**
126
102
  * Asynchronously updates one entry in a database or adds a new one if it doesn't exist.
127
103
  */
128
104
  async updateOneOrAdd(collection, search, arg, add_arg = {}, context = {}, id_gen = true) {
129
- const searchStr = typeof search === "function" ? search.toString() : search;
130
- const argStr = typeof arg === "function" ? arg.toString() : arg;
131
- return await this._request("updateOneOrAdd", { collection, search: searchStr, arg: argStr, add_arg, id_gen, context });
105
+ return await this._request("updateOneOrAdd", [collection, search, arg, add_arg, id_gen, context]);
132
106
  }
133
107
  /**
134
108
  * Removes a database collection from the file system.
135
109
  */
136
110
  async removeCollection(name) {
137
- return await this._request("removeCollection", { name });
111
+ return await this._request("removeCollection", [name]);
138
112
  }
139
113
  }
140
114
  export default DataBaseRemote;
@@ -1,4 +1,4 @@
1
- import { Remote, RequestData } from "./remote";
1
+ import { Remote } from "./remote.js";
2
2
  /**
3
3
  * A class representing a graph database.
4
4
  * Uses a remote database.
@@ -13,7 +13,7 @@ declare class GraphRemote {
13
13
  /**
14
14
  * Make a request to the remote database.
15
15
  */
16
- _request(type: string, data: RequestData): Promise<any>;
16
+ _request(type: string, params?: any[]): Promise<any>;
17
17
  /**
18
18
  * Adds an edge between two nodes.
19
19
  */
@@ -1,4 +1,4 @@
1
- import got from "got";
1
+ import ky from "ky";
2
2
  /**
3
3
  * A class representing a graph database.
4
4
  * Uses a remote database.
@@ -15,74 +15,75 @@ class GraphRemote {
15
15
  /**
16
16
  * Make a request to the remote database.
17
17
  */
18
- async _request(type, data) {
19
- data.db = this.remote.name;
20
- const res = await got.post(this.remote.url + "/db/graph/" + type, {
21
- // @ts-ignore
22
- body: data,
18
+ async _request(type, params = []) {
19
+ const data = {
20
+ db: this.remote.name,
21
+ params
22
+ };
23
+ const res = await ky.post(this.remote.url + "/db/" + type, {
24
+ json: data,
23
25
  headers: {
24
26
  "Authorization": this.remote.auth
25
27
  },
26
- json: true,
27
- responseType: "json"
28
- });
29
- if (res.body.err)
30
- throw new Error(res.body.msg);
31
- return res.body.result;
28
+ throwHttpErrors: false
29
+ }).json();
30
+ if (res.err)
31
+ throw new Error(res.msg);
32
+ return res.result;
32
33
  }
33
34
  /**
34
35
  * Adds an edge between two nodes.
35
36
  */
36
37
  async add(collection, nodeA, nodeB) {
37
- return await this._request("add", { collection, nodeA, nodeB });
38
+ return await this._request("add", [collection, nodeA, nodeB]);
38
39
  }
39
40
  /**
40
41
  * Removes an edge between two nodes.
41
42
  */
42
43
  async remove(collection, nodeA, nodeB) {
43
- return await this._request("remove", { collection, nodeA, nodeB });
44
+ return await this._request("remove", [collection, nodeA, nodeB]);
44
45
  }
45
46
  /**
46
47
  * Finds all edges with either node equal to `node`.
47
48
  */
48
49
  async find(collection, node) {
49
- return await this._request("find", { collection, node });
50
+ return await this._request("find", [collection, node]);
50
51
  }
51
52
  /**
52
53
  * Finds one edge with either node equal to `nodeA` and the other equal to `nodeB`.
53
54
  */
54
55
  async findOne(collection, nodeA, nodeB) {
55
- return await this._request("findOne", { collection, nodeA, nodeB });
56
+ return await this._request("findOne", [collection, nodeA, nodeB]);
56
57
  }
57
58
  /**
58
59
  * Get all edges in the collection.
59
60
  */
60
61
  async getAll(collection) {
61
- return await this._request("getAll", { collection });
62
+ return await this._request("getAll", [collection]);
62
63
  }
63
64
  /**
64
65
  * Get the names of all available databases.
65
66
  */
66
67
  async getCollections() {
67
- return await this._request("getCollections", {});
68
+ return await this._request("getCollections", []);
68
69
  }
69
70
  /**
70
71
  * Check and create the specified collection if it doesn't exist.
71
72
  */
72
73
  async checkCollection(collection) {
73
- return await this._request("checkCollection", { collection });
74
+ return await this._request("checkCollection", [collection]);
74
75
  }
75
76
  /**
76
77
  * Check if a collection exists.
77
78
  */
78
79
  async issetCollection(collection) {
79
- return await this._request("issetCollection", { collection });
80
+ return await this._request("issetCollection", [collection]);
80
81
  }
81
82
  /**
82
83
  * Remove the specified collection.
83
84
  */
84
85
  removeCollection(collection) {
85
- return this._request("removeCollection", { collection });
86
+ return this._request("removeCollection", [collection]);
86
87
  }
87
88
  }
88
89
  export default GraphRemote;
@@ -4,10 +4,9 @@ export interface Remote {
4
4
  auth: string;
5
5
  }
6
6
  export interface RequestData {
7
- collection?: string;
8
7
  db?: string;
9
8
  keys?: string[];
10
- [key: string]: any;
9
+ params?: Record<string, any>;
11
10
  }
12
11
  export interface findOptsRemote {
13
12
  select?: string[];
@@ -2,17 +2,11 @@
2
2
  * Parses given string into a JSON object. If the string does not start with
3
3
  * a {, it is wrapped in one. This allows for a shorthand when
4
4
  * storing/reading data from a file.
5
- *
6
- * @param {string} data
7
- * @returns {Object}
8
5
  */
9
- export declare function parse(data: any): any;
6
+ export declare function parse(data: string): any;
10
7
  /**
11
8
  * Converts given object to a string. If the string is a valid json5, it is
12
9
  * returned as is. If it is a valid json5 wrapped in {}, the curly brackets
13
10
  * are removed. Otherwise the string is wrapped in {}.
14
- *
15
- * @param {Object} data
16
- * @return {String}
17
11
  */
18
12
  export declare function stringify(data: any): any;
@@ -3,9 +3,6 @@ import json5 from "json5";
3
3
  * Parses given string into a JSON object. If the string does not start with
4
4
  * a {, it is wrapped in one. This allows for a shorthand when
5
5
  * storing/reading data from a file.
6
- *
7
- * @param {string} data
8
- * @returns {Object}
9
6
  */
10
7
  export function parse(data) {
11
8
  if (!data.startsWith("{"))
@@ -16,9 +13,6 @@ export function parse(data) {
16
13
  * Converts given object to a string. If the string is a valid json5, it is
17
14
  * returned as is. If it is a valid json5 wrapped in {}, the curly brackets
18
15
  * are removed. Otherwise the string is wrapped in {}.
19
- *
20
- * @param {Object} data
21
- * @return {String}
22
16
  */
23
17
  export function stringify(data) {
24
18
  data = json5.stringify(data);
package/dist/esm/gen.d.ts CHANGED
@@ -1,5 +1,8 @@
1
- import Id from "./types/Id";
1
+ import Id from "./types/Id.js";
2
2
  /**
3
- * Generates a unique identifier based on specified parts.
3
+ * Generates a unique random identifier based on time and parts.
4
+ *
5
+ * @param {number[]} [parts] - an array of lengths of parts of the identifier
6
+ * @returns {Id} - a new unique identifier
4
7
  */
5
- export default function genId(parts?: number | number[], fill?: number): Id;
8
+ export default function genId(parts?: number[]): Id;
package/dist/esm/gen.js CHANGED
@@ -1,75 +1,134 @@
1
1
  const usedIdsMap = new Map();
2
+ let lastId;
3
+ const recentIdsTimestamps = [];
4
+ let startIndex = 0;
5
+ let lastGeneratedMs = 0;
6
+ let lastRandomValue = 0;
2
7
  /**
3
- * Generates a unique identifier based on specified parts.
8
+ * Generates a unique random identifier based on time and parts.
9
+ *
10
+ * @param {number[]} [parts] - an array of lengths of parts of the identifier
11
+ * @returns {Id} - a new unique identifier
4
12
  */
5
- export default function genId(parts = null, fill = 1) {
6
- parts = changeInputToPartsArray(parts, fill);
13
+ export default function genId(parts = null) {
14
+ if (parts === null)
15
+ parts = [1, 1];
7
16
  const time = getTime();
8
- const id = getUniqueRandom(time, parts);
17
+ const id = getUniqueRandom({
18
+ time,
19
+ partsSchema: parts,
20
+ s: 0,
21
+ });
9
22
  return id;
10
23
  }
11
24
  /**
12
25
  * Generates a unique random identifier based on time and parts.
13
- * @param time - The current time in a base36 string format.
14
- * @param parts - An array of parts to be used for generating the identifier.
15
- * @param s - Recursion counter for handling collision (default: 0).
16
- * @returns {string} The unique random identifier.
17
26
  */
18
- function getUniqueRandom(time, partsA, s = 0) {
19
- const parts = partsA.map(l => getRandom(l));
20
- const id = [time, ...parts].join("-");
21
- if (usedIdsMap.has(id)) {
22
- s++;
23
- if (s < 25)
24
- return getUniqueRandom(time, partsA, s);
25
- partsA = addOneToPods(partsA);
26
- time = getTime();
27
- return getUniqueRandom(time, partsA);
27
+ function getUniqueRandom(opts) {
28
+ while (true) {
29
+ let minValue = 0;
30
+ if (lastId) {
31
+ const parts = lastId.split("-");
32
+ const lastTime = parts.shift();
33
+ if (lastTime === opts.time) {
34
+ const int36 = parts.join("");
35
+ minValue = parseInt(int36, 36) + 1;
36
+ }
37
+ }
38
+ const partsLengthSum = opts.partsSchema.reduce((acc, num) => acc + num, 0);
39
+ const partsData = generateBase36InRange(minValue, partsLengthSum);
40
+ const parts = splitStringByArray(opts.partsSchema, partsData);
41
+ const id = [opts.time, ...parts].join("-");
42
+ if (!usedIdsMap.has(id)) {
43
+ usedIdsMap.set(id, true);
44
+ setTimeout(() => usedIdsMap.delete(id), 1000);
45
+ lastId = id;
46
+ return id;
47
+ }
48
+ opts.s++;
49
+ if (opts.s >= partsLengthSum) {
50
+ opts.time = getTime();
51
+ opts.s = 0;
52
+ }
28
53
  }
29
- usedIdsMap.set(id, Date.now() + 2000);
30
- usedIdsMap.forEach((value, key) => {
31
- if (value < Date.now())
32
- usedIdsMap.delete(key);
33
- });
34
- return id;
35
54
  }
36
55
  /**
37
- * Generates a random string of base36 characters.
56
+ * Tracks the current load of the application by counting the number of ids that have been generated in the last second.
57
+ * @returns The number of ids that have been generated in the last second.
38
58
  */
39
- function getRandom(unix) {
40
- return (Math.floor(Math.random() * Math.pow(36, unix))).toString(36);
59
+ function trackLoad() {
60
+ const now = Date.now();
61
+ recentIdsTimestamps.push(now);
62
+ while (startIndex < recentIdsTimestamps.length && recentIdsTimestamps[startIndex] < now - 1) {
63
+ startIndex++;
64
+ }
65
+ return recentIdsTimestamps.length - startIndex;
41
66
  }
42
67
  /**
43
- * Gets the current time in a base36 string format.
68
+ * Generates a base-36 encoded string with a specified length based on a random value within a range.
69
+ *
70
+ * The function calculates a random value within the base-36 range determined by the provided
71
+ * `minValue` and `length`. It uses a bias mechanism to adjust the randomness based on the
72
+ * current load, ensuring unique generation over short periods. If the system load is low or
73
+ * the current millisecond has changed, a new random value is generated. Otherwise, the random
74
+ * value is incremented by a small amount with certain probabilities.
75
+ *
76
+ * @param minValue - The minimum value for the base-36 encoded number.
77
+ * @param length - The length of the resulting base-36 string.
78
+ * @returns A base-36 encoded string representation of the random value, padded to the specified length.
44
79
  */
45
- function getTime() {
46
- return Math.floor(new Date().getTime() / 1000).toString(36);
80
+ function generateBase36InRange(minValue, length) {
81
+ const maxValue = Math.pow(36, length) - 1;
82
+ const load = trackLoad();
83
+ const currentMs = Date.now();
84
+ if (load < 3 || currentMs !== lastGeneratedMs) {
85
+ lastRandomValue = biasedRandomInRange(minValue, maxValue);
86
+ lastGeneratedMs = currentMs;
87
+ }
88
+ else {
89
+ const rand = Math.random();
90
+ if (rand < 0.6) {
91
+ lastRandomValue += 1;
92
+ }
93
+ else if (rand < 0.9) {
94
+ lastRandomValue += 2;
95
+ }
96
+ else {
97
+ lastRandomValue = biasedRandomInRange(lastRandomValue, maxValue);
98
+ }
99
+ }
100
+ return lastRandomValue.toString(36).padStart(length, "0");
47
101
  }
48
102
  /**
49
- * Adds one to each part of the input array.
103
+ * Generates a random number between the specified range, but with a bias towards the lower
104
+ * end of the range. The bias is calculated as the cube root of the random value, which
105
+ * will make the random value more likely to be closer to the minimum value.
106
+ * @param min - The minimum value of the range.
107
+ * @param max - The maximum value of the range.
108
+ * @returns A random number between the specified range, with a bias towards the lower end.
50
109
  */
51
- function addOneToPods(array) {
52
- const sum = array.reduce((acc, current) => acc + current, 0);
53
- const num = sum + 1;
54
- const len = array.length;
55
- const result = [];
56
- const quotient = Math.floor(num / len);
57
- const remainder = num % len;
58
- for (let i = 0; i < len; i++) {
59
- if (i < remainder)
60
- result.push(quotient + 1);
61
- else
62
- result.push(quotient);
63
- }
64
- return result;
110
+ function biasedRandomInRange(min, max) {
111
+ let randomValue = min;
112
+ const bias = Math.pow(Math.random(), 3);
113
+ randomValue = Math.floor(min + (max - min) * bias);
114
+ return Math.min(randomValue, max);
65
115
  }
66
116
  /**
67
- * Converts input to an array of parts.
117
+ * Splits a string into an array of substrings, where each substring is determined by
118
+ * the values in the provided array.
119
+ *
120
+ * @param arr - An array of numbers, where each number represents the length of a substring.
121
+ * @param str - The string to split.
122
+ * @returns An array of substrings, where each element is a substring of the original string,
123
+ * determined by the corresponding element in the provided array.
68
124
  */
69
- function changeInputToPartsArray(parts = null, fill = 1) {
70
- if (Array.isArray(parts))
71
- return parts;
72
- if (typeof parts == "number")
73
- return Array(parts).fill(fill);
74
- return [1, 1];
125
+ function splitStringByArray(arr, str) {
126
+ let start = 0;
127
+ return arr.map(length => str.slice(start, start += length));
128
+ }
129
+ /**
130
+ * Gets the current time in a base36 string format.
131
+ */
132
+ function getTime() {
133
+ return new Date().getTime().toString(36);
75
134
  }
@@ -4,61 +4,31 @@ import { DbFindOpts } from "./types/options.js";
4
4
  export interface Databases {
5
5
  [key: string]: DataBase;
6
6
  }
7
+ interface RelationConfig {
8
+ from: string;
9
+ localField: string;
10
+ foreignField: string;
11
+ as?: string;
12
+ multiple?: boolean;
13
+ }
7
14
  declare class Relation {
8
- databases: Databases;
15
+ private databases;
9
16
  constructor(databases: Databases);
10
17
  /**
11
- * Resolves the relation path in format 'dbName.collectionName'
12
- */
13
- _resolvePath(path: string): {
14
- db: DataBase;
15
- collection: string;
16
- };
18
+ * Resolves the relation path in format 'dbName.collectionName'.
19
+ */
20
+ private _resolvePath;
17
21
  /**
18
- * Processes relations for a single item
19
- * @param {Object} item - Item to process relations for
20
- * @param {Object} relations - Relations configuration
21
- * @returns {Promise<Object>} Processed item with resolved relations
22
+ * Processes relations for a single item.
22
23
  */
23
- _processItemRelations(item: Object, relations: Object): Promise<{
24
- constructor: Function;
25
- toString(): string;
26
- toLocaleString(): string;
27
- valueOf(): Object;
28
- hasOwnProperty(v: PropertyKey): boolean;
29
- isPrototypeOf(v: Object): boolean;
30
- propertyIsEnumerable(v: PropertyKey): boolean;
31
- }>;
24
+ private _processItemRelations;
32
25
  /**
33
- * Finds items with relations
34
- * @param path - Path in format 'dbName.collectionName'
35
- * @param search - Search query or function
36
- * @param relations - Relations configuration
37
- * @param options - Search options
26
+ * Finds multiple items with relations.
38
27
  */
39
- find(path: string, search: Search, relations?: {}, options?: DbFindOpts): Promise<{
40
- constructor: Function;
41
- toString(): string;
42
- toLocaleString(): string;
43
- valueOf(): Object;
44
- hasOwnProperty(v: PropertyKey): boolean;
45
- isPrototypeOf(v: Object): boolean;
46
- propertyIsEnumerable(v: PropertyKey): boolean;
47
- }[]>;
28
+ find(path: string, search: Search, relations?: Record<string, RelationConfig>, options?: DbFindOpts): Promise<Record<string, any>[]>;
48
29
  /**
49
- * Finds one item with relations
50
- * @param path - Path in format 'dbName.collectionName'
51
- * @param search - Search query or function
52
- * @param relations - Relations configuration
30
+ * Finds a single item with relations.
53
31
  */
54
- findOne(path: string, search: Search, relations?: Object): Promise<{
55
- constructor: Function;
56
- toString(): string;
57
- toLocaleString(): string;
58
- valueOf(): Object;
59
- hasOwnProperty(v: PropertyKey): boolean;
60
- isPrototypeOf(v: Object): boolean;
61
- propertyIsEnumerable(v: PropertyKey): boolean;
62
- }>;
32
+ findOne(path: string, search: Search, relations?: Record<string, RelationConfig>): Promise<Record<string, any> | null>;
63
33
  }
64
34
  export default Relation;