@wxn0brp/db-core 0.0.1 → 0.0.2
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 +15 -3
- package/dist/version.js +1 -1
- package/package.json +10 -1
- package/.github/workflows/build-relase.yml +0 -25
- package/.github/workflows/build.yml +0 -20
- package/.github/workflows/types.yml +0 -89
- package/CHANGELOG.md +0 -9
- package/src/base/actions.ts +0 -71
- package/src/base/db.ts +0 -75
- package/src/customFileCpu.ts +0 -100
- package/src/db/memory.ts +0 -177
- package/src/db/valthera.ts +0 -132
- package/src/helpers/CollectionManager.ts +0 -67
- package/src/helpers/eventEmiter.ts +0 -73
- package/src/helpers/executor.ts +0 -55
- package/src/helpers/gen.ts +0 -154
- package/src/helpers/relation.ts +0 -192
- package/src/helpers/updateOneOrAdd.ts +0 -24
- package/src/index.ts +0 -25
- package/src/types/Id.ts +0 -3
- package/src/types/arg.ts +0 -15
- package/src/types/data.ts +0 -4
- package/src/types/export.ts +0 -13
- package/src/types/fileCpu.ts +0 -78
- package/src/types/options.ts +0 -22
- package/src/types/query.ts +0 -16
- package/src/types/relation.ts +0 -34
- package/src/types/searchOpts.ts +0 -78
- package/src/types/types.ts +0 -3
- package/src/types/updater.ts +0 -33
- package/src/types/valthera.ts +0 -38
- package/src/utils/hasFields.ts +0 -18
- package/src/utils/hasFieldsAdvanced.ts +0 -181
- package/src/utils/sort.ts +0 -25
- package/src/utils/updateFindObject.ts +0 -35
- package/src/utils/updateObject.ts +0 -156
- package/src/version.ts +0 -1
- package/suglite.json +0 -10
- package/tsconfig.json +0 -22
package/src/db/valthera.ts
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import { version } from "../version";
|
|
3
|
-
import { UniversalEventEmitter } from "../helpers/eventEmiter";
|
|
4
|
-
import dbActionBase from "../base/actions";
|
|
5
|
-
import CollectionManager from "../helpers/CollectionManager";
|
|
6
|
-
import executorC from "../helpers/executor";
|
|
7
|
-
import { Arg, Search, Updater } from "../types/arg";
|
|
8
|
-
import Data from "../types/data";
|
|
9
|
-
import { DbOpts, DbFindOpts, FindOpts } from "../types/options";
|
|
10
|
-
import { VContext } from "../types/types";
|
|
11
|
-
import { ValtheraCompatible } from "../types/valthera";
|
|
12
|
-
|
|
13
|
-
type DbActionsFns = keyof {
|
|
14
|
-
[K in keyof dbActionBase as dbActionBase[K] extends (...args: any[]) => any ? K : never]: any;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Represents a database management class for performing CRUD operations.
|
|
19
|
-
* @class
|
|
20
|
-
*/
|
|
21
|
-
class ValtheraClass implements ValtheraCompatible {
|
|
22
|
-
dbAction: dbActionBase;
|
|
23
|
-
executor: executorC;
|
|
24
|
-
emiter: UniversalEventEmitter;
|
|
25
|
-
version = version;
|
|
26
|
-
|
|
27
|
-
constructor(options: DbOpts = {}) {
|
|
28
|
-
this.dbAction = options.dbAction || new dbActionBase();
|
|
29
|
-
this.executor = options.executor || new executorC();
|
|
30
|
-
this.emiter = new UniversalEventEmitter();
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
private async execute<T>(name: DbActionsFns, ...args: any[]) {
|
|
34
|
-
const result = await this.executor.addOp(this.dbAction[name].bind(this.dbAction), ...args) as T;
|
|
35
|
-
if (this.emiter.listenerCount(name) !== 0) this.emiter.emit(name, args, result);
|
|
36
|
-
if (this.emiter.listenerCount("*") !== 0) this.emiter.emit("*", name, args, result);
|
|
37
|
-
return result;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Create a new instance of a CollectionManager class.
|
|
42
|
-
*/
|
|
43
|
-
c(collection: string) {
|
|
44
|
-
return new CollectionManager(this, collection);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Get the names of all available databases.
|
|
49
|
-
*/
|
|
50
|
-
async getCollections() {
|
|
51
|
-
return await this.execute<string[]>("getCollections");
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Check and create the specified collection if it doesn't exist.
|
|
56
|
-
*/
|
|
57
|
-
async checkCollection(collection: string) {
|
|
58
|
-
return await this.execute<boolean>("checkCollection", { collection });
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Check if a collection exists.
|
|
63
|
-
*/
|
|
64
|
-
async issetCollection(collection: string) {
|
|
65
|
-
return await this.execute<boolean>("issetCollection", { collection });
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Add data to a database.
|
|
70
|
-
*/
|
|
71
|
-
async add<T = Data>(collection: string, data: Arg, id_gen: boolean = true) {
|
|
72
|
-
return await this.execute<T>("add", { collection, data, id_gen });
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Find data in a database.
|
|
77
|
-
*/
|
|
78
|
-
async find<T = Data>(collection: string, search: Search, context: VContext = {}, dbFindOpts: DbFindOpts = {}, findOpts: FindOpts = {}) {
|
|
79
|
-
return await this.execute<T[]>("find", { collection, search, context, dbFindOpts, findOpts });
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Find one data entry in a database.
|
|
84
|
-
*/
|
|
85
|
-
async findOne<T = Data>(collection: string, search: Search, context: VContext = {}, findOpts: FindOpts = {}) {
|
|
86
|
-
return await this.execute<T | null>("findOne", { collection, search, context, findOpts });
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Update data in a database.
|
|
91
|
-
*/
|
|
92
|
-
async update(collection: string, search: Search, updater: Updater, context = {}) {
|
|
93
|
-
return await this.execute<boolean>("update", { collection, search, updater, context });
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Update one data entry in a database.
|
|
98
|
-
*/
|
|
99
|
-
async updateOne(collection: string, search: Search, updater: Updater, context: VContext = {}) {
|
|
100
|
-
return await this.execute<boolean>("updateOne", { collection, search, updater, context });
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Remove data from a database.
|
|
105
|
-
*/
|
|
106
|
-
async remove(collection: string, search: Search, context: VContext = {}) {
|
|
107
|
-
return await this.execute<boolean>("remove", { collection, search, context });
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Remove one data entry from a database.
|
|
112
|
-
*/
|
|
113
|
-
async removeOne(collection: string, search: Search, context: VContext = {}) {
|
|
114
|
-
return await this.execute<boolean>("removeOne", { collection, search, context });
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Asynchronously updates one entry in a database or adds a new one if it doesn't exist.
|
|
119
|
-
*/
|
|
120
|
-
async updateOneOrAdd(collection: string, search: Search, updater: Updater, add_arg: Arg = {}, context: VContext = {}, id_gen: boolean = true) {
|
|
121
|
-
return await this.execute<boolean>("updateOneOrAdd", { collection, search, updater, add_arg, context, id_gen });
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Removes a database collection from the file system.
|
|
126
|
-
*/
|
|
127
|
-
async removeCollection(collection: string) {
|
|
128
|
-
return await this.execute<boolean>("removeCollection", { collection });
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
export default ValtheraClass;
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { Arg, Search, Updater } from "../types/arg";
|
|
2
|
-
import { DbFindOpts, FindOpts } from "../types/options";
|
|
3
|
-
import { VContext } from "../types/types";
|
|
4
|
-
import Data from "../types/data";
|
|
5
|
-
import { ValtheraCompatible } from "../types/valthera";
|
|
6
|
-
|
|
7
|
-
class CollectionManager {
|
|
8
|
-
constructor(private db: ValtheraCompatible, private collection: string) {}
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Add data to a database.
|
|
12
|
-
*/
|
|
13
|
-
async add<T = Data>(data: Arg, id_gen: boolean = true) {
|
|
14
|
-
return await this.db.add(this.collection, data, id_gen) as T;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Find data in a database.
|
|
19
|
-
*/
|
|
20
|
-
async find<T = Data>(search: Search, context: VContext = {}, options: DbFindOpts = {}, findOpts: FindOpts = {}) {
|
|
21
|
-
return await this.db.find(this.collection, search, context, options, findOpts) as T[];
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Find one data entry in a database.
|
|
26
|
-
*/
|
|
27
|
-
async findOne<T = Data>(search: Search, context: VContext = {}, findOpts: FindOpts = {}) {
|
|
28
|
-
return await this.db.findOne(this.collection, search, context, findOpts) as (T | null);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Update data in a database.
|
|
33
|
-
*/
|
|
34
|
-
async update(search: Search, updater: Updater, context: VContext = {}) {
|
|
35
|
-
return await this.db.update(this.collection, search, updater, context) as boolean;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Update one data entry in a database.
|
|
40
|
-
*/
|
|
41
|
-
async updateOne(search: Search, updater: Updater, context: VContext = {}) {
|
|
42
|
-
return await this.db.updateOne(this.collection, search, updater, context) as boolean;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Remove data from a database.
|
|
47
|
-
*/
|
|
48
|
-
async remove(search: Search, context: VContext = {}) {
|
|
49
|
-
return await this.db.remove(this.collection, search, context) as boolean;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Remove one data entry from a database.
|
|
54
|
-
*/
|
|
55
|
-
async removeOne(search: Search, context: VContext = {}) {
|
|
56
|
-
return await this.db.removeOne(this.collection, search, context) as boolean;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Asynchronously updates one entry in a database or adds a new one if it doesn't exist.
|
|
61
|
-
*/
|
|
62
|
-
async updateOneOrAdd(search: Search, updater: Updater, add_arg: Arg = {}, context: VContext = {}, id_gen: boolean = true) {
|
|
63
|
-
return await this.db.updateOneOrAdd(this.collection, search, updater, add_arg, context, id_gen) as boolean;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export default CollectionManager;
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
export class UniversalEventEmitter {
|
|
2
|
-
private _events: { [event: string]: Function[] } = {};
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Registers an event listener
|
|
6
|
-
* @param {string} event - event name
|
|
7
|
-
* @param {Function} listener - function to be called when event occurs
|
|
8
|
-
*/
|
|
9
|
-
public on(event: string, listener: Function): void {
|
|
10
|
-
if (!this._events[event])
|
|
11
|
-
this._events[event] = [];
|
|
12
|
-
this._events[event].push(listener);
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Registers a one-time event listener
|
|
17
|
-
* @param {string} event - event name
|
|
18
|
-
* @param {Function} listener - function to be called once
|
|
19
|
-
*/
|
|
20
|
-
public once(event: string, listener: Function): void {
|
|
21
|
-
const onceListener = (...args: any[]) => {
|
|
22
|
-
this.off(event, onceListener);
|
|
23
|
-
listener(...args);
|
|
24
|
-
};
|
|
25
|
-
this.on(event, onceListener);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Removes an event listener
|
|
30
|
-
* @param {string} event - event name
|
|
31
|
-
* @param {Function} [listener] - optional: specific listener to remove
|
|
32
|
-
*/
|
|
33
|
-
public off(event?: string, listener?: Function): void {
|
|
34
|
-
if (!event) {
|
|
35
|
-
// Remove all events
|
|
36
|
-
this._events = {};
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
if (!listener) {
|
|
41
|
-
// Remove all listeners for the given event
|
|
42
|
-
delete this._events[event];
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Remove specific listener
|
|
47
|
-
if (this._events[event]) {
|
|
48
|
-
this._events[event] = this._events[event].filter(l => l !== listener);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Emits an event
|
|
54
|
-
* @param {string} event - event name
|
|
55
|
-
* @param {...any} args - arguments to be passed to listeners
|
|
56
|
-
*/
|
|
57
|
-
public emit(event: string, ...args: any[]): void {
|
|
58
|
-
const listeners = this._events[event];
|
|
59
|
-
if (listeners && listeners.length > 0) {
|
|
60
|
-
listeners.forEach(listener => {
|
|
61
|
-
listener(...args);
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Returns the number of listeners for the given event
|
|
68
|
-
*/
|
|
69
|
-
public listenerCount(event: string): number {
|
|
70
|
-
return this._events[event]?.length || 0;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
package/src/helpers/executor.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
interface Task {
|
|
2
|
-
func: Function;
|
|
3
|
-
param: any[];
|
|
4
|
-
resolve: Function;
|
|
5
|
-
reject: Function;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* A simple executor for queuing and executing asynchronous operations sequentially.
|
|
10
|
-
* @class
|
|
11
|
-
*/
|
|
12
|
-
class executorC {
|
|
13
|
-
quote: Task[];
|
|
14
|
-
isExecuting: boolean;
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Create a new executor instance.
|
|
18
|
-
* @constructor
|
|
19
|
-
*/
|
|
20
|
-
constructor() {
|
|
21
|
-
this.quote = [];
|
|
22
|
-
this.isExecuting = false;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Add an asynchronous operation to the execution queue.
|
|
27
|
-
*/
|
|
28
|
-
async addOp(func: Function, ...param) {
|
|
29
|
-
return await new Promise((resolve, reject) => {
|
|
30
|
-
this.quote.push({
|
|
31
|
-
func,
|
|
32
|
-
param,
|
|
33
|
-
resolve,
|
|
34
|
-
reject
|
|
35
|
-
});
|
|
36
|
-
this.execute();
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Execute the queued asynchronous operations sequentially.
|
|
42
|
-
*/
|
|
43
|
-
async execute() {
|
|
44
|
-
if (this.isExecuting) return;
|
|
45
|
-
this.isExecuting = true;
|
|
46
|
-
while (this.quote.length > 0) {
|
|
47
|
-
let q = this.quote.shift();
|
|
48
|
-
let res = await q.func(...q.param);
|
|
49
|
-
q.resolve(res)
|
|
50
|
-
}
|
|
51
|
-
this.isExecuting = false;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export default executorC;
|
package/src/helpers/gen.ts
DELETED
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
import Id from "../types/Id";
|
|
2
|
-
|
|
3
|
-
const usedIdsMap = new Map();
|
|
4
|
-
let lastId: Id;
|
|
5
|
-
const recentIdsTimestamps: number[] = [];
|
|
6
|
-
let startIndex = 0;
|
|
7
|
-
let lastGeneratedMs = 0;
|
|
8
|
-
let lastRandomValue = 0;
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Generates a unique random identifier based on time and parts.
|
|
12
|
-
*
|
|
13
|
-
* @param {number[]} [parts] - an array of lengths of parts of the identifier
|
|
14
|
-
* @returns {Id} - a new unique identifier
|
|
15
|
-
*/
|
|
16
|
-
export default function genId(parts: number[] = null): Id {
|
|
17
|
-
if (parts === null) parts = [1, 1];
|
|
18
|
-
|
|
19
|
-
const time = getTime();
|
|
20
|
-
const id = getUniqueRandom({
|
|
21
|
-
time,
|
|
22
|
-
partsSchema: parts,
|
|
23
|
-
s: 0,
|
|
24
|
-
});
|
|
25
|
-
return id;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
interface GetUniqueRandomOpts {
|
|
29
|
-
time: string,
|
|
30
|
-
partsSchema: number[],
|
|
31
|
-
s: number
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Generates a unique random identifier based on time and parts.
|
|
36
|
-
*/
|
|
37
|
-
function getUniqueRandom(opts: GetUniqueRandomOpts): string {
|
|
38
|
-
while (true) {
|
|
39
|
-
let minValue = 0;
|
|
40
|
-
if (lastId) {
|
|
41
|
-
const parts = lastId.split("-");
|
|
42
|
-
const lastTime = parts.shift();
|
|
43
|
-
if (lastTime === opts.time) {
|
|
44
|
-
const int36 = parts.join("");
|
|
45
|
-
minValue = parseInt(int36, 36) + 1;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const partsLengthSum = opts.partsSchema.reduce((acc, num) => acc + num, 0);
|
|
50
|
-
const partsData = generateBase36InRange(minValue, partsLengthSum);
|
|
51
|
-
const parts = splitStringByArray(opts.partsSchema, partsData);
|
|
52
|
-
|
|
53
|
-
const id = [opts.time, ...parts].join("-");
|
|
54
|
-
|
|
55
|
-
if (!usedIdsMap.has(id)) {
|
|
56
|
-
usedIdsMap.set(id, true);
|
|
57
|
-
setTimeout(() => usedIdsMap.delete(id), 1000);
|
|
58
|
-
lastId = id;
|
|
59
|
-
return id;
|
|
60
|
-
}
|
|
61
|
-
opts.s++;
|
|
62
|
-
if (opts.s >= partsLengthSum) {
|
|
63
|
-
opts.time = getTime();
|
|
64
|
-
opts.s = 0;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Tracks the current load of the application by counting the number of ids that have been generated in the last second.
|
|
71
|
-
* @returns The number of ids that have been generated in the last second.
|
|
72
|
-
*/
|
|
73
|
-
function trackLoad() {
|
|
74
|
-
const now = Date.now();
|
|
75
|
-
recentIdsTimestamps.push(now);
|
|
76
|
-
|
|
77
|
-
while (startIndex < recentIdsTimestamps.length && recentIdsTimestamps[startIndex] < now - 1) {
|
|
78
|
-
startIndex++;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
return recentIdsTimestamps.length - startIndex;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Generates a base-36 encoded string with a specified length based on a random value within a range.
|
|
86
|
-
*
|
|
87
|
-
* The function calculates a random value within the base-36 range determined by the provided
|
|
88
|
-
* `minValue` and `length`. It uses a bias mechanism to adjust the randomness based on the
|
|
89
|
-
* current load, ensuring unique generation over short periods. If the system load is low or
|
|
90
|
-
* the current millisecond has changed, a new random value is generated. Otherwise, the random
|
|
91
|
-
* value is incremented by a small amount with certain probabilities.
|
|
92
|
-
*
|
|
93
|
-
* @param minValue - The minimum value for the base-36 encoded number.
|
|
94
|
-
* @param length - The length of the resulting base-36 string.
|
|
95
|
-
* @returns A base-36 encoded string representation of the random value, padded to the specified length.
|
|
96
|
-
*/
|
|
97
|
-
|
|
98
|
-
function generateBase36InRange(minValue: number, length: number): string {
|
|
99
|
-
const maxValue = Math.pow(36, length) - 1;
|
|
100
|
-
const load = trackLoad();
|
|
101
|
-
const currentMs = Date.now();
|
|
102
|
-
|
|
103
|
-
if (load < 3 || currentMs !== lastGeneratedMs) {
|
|
104
|
-
lastRandomValue = biasedRandomInRange(minValue, maxValue);
|
|
105
|
-
lastGeneratedMs = currentMs;
|
|
106
|
-
} else {
|
|
107
|
-
const rand = Math.random();
|
|
108
|
-
if (rand < 0.6) {
|
|
109
|
-
lastRandomValue += 1;
|
|
110
|
-
} else if (rand < 0.9) {
|
|
111
|
-
lastRandomValue += 2;
|
|
112
|
-
} else {
|
|
113
|
-
lastRandomValue = biasedRandomInRange(lastRandomValue, maxValue);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
return lastRandomValue.toString(36).padStart(length, "0");
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* Generates a random number between the specified range, but with a bias towards the lower
|
|
122
|
-
* end of the range. The bias is calculated as the cube root of the random value, which
|
|
123
|
-
* will make the random value more likely to be closer to the minimum value.
|
|
124
|
-
* @param min - The minimum value of the range.
|
|
125
|
-
* @param max - The maximum value of the range.
|
|
126
|
-
* @returns A random number between the specified range, with a bias towards the lower end.
|
|
127
|
-
*/
|
|
128
|
-
function biasedRandomInRange(min: number, max: number): number {
|
|
129
|
-
let randomValue = min;
|
|
130
|
-
const bias = Math.pow(Math.random(), 3);
|
|
131
|
-
randomValue = Math.floor(min + (max - min) * bias);
|
|
132
|
-
return Math.min(randomValue, max);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Splits a string into an array of substrings, where each substring is determined by
|
|
137
|
-
* the values in the provided array.
|
|
138
|
-
*
|
|
139
|
-
* @param arr - An array of numbers, where each number represents the length of a substring.
|
|
140
|
-
* @param str - The string to split.
|
|
141
|
-
* @returns An array of substrings, where each element is a substring of the original string,
|
|
142
|
-
* determined by the corresponding element in the provided array.
|
|
143
|
-
*/
|
|
144
|
-
function splitStringByArray(arr: number[], str: string) {
|
|
145
|
-
let start = 0;
|
|
146
|
-
return arr.map(length => str.slice(start, start += length));
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Gets the current time in a base36 string format.
|
|
151
|
-
*/
|
|
152
|
-
function getTime() {
|
|
153
|
-
return new Date().getTime().toString(36);
|
|
154
|
-
}
|
package/src/helpers/relation.ts
DELETED
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import { Search } from "../types/arg";
|
|
2
|
-
import { DbFindOpts } from "../types/options";
|
|
3
|
-
import { RelationTypes } from "../types/relation";
|
|
4
|
-
|
|
5
|
-
function pickByPath(obj: any, paths: string[][]): any {
|
|
6
|
-
const result = {};
|
|
7
|
-
for (const path of paths) {
|
|
8
|
-
let src = obj;
|
|
9
|
-
let dst = result;
|
|
10
|
-
for (let i = 0; i < path.length; i++) {
|
|
11
|
-
const k = path[i];
|
|
12
|
-
if (src == null) break;
|
|
13
|
-
if (i === path.length - 1) {
|
|
14
|
-
dst[k] = src[k];
|
|
15
|
-
} else {
|
|
16
|
-
dst[k] ||= {};
|
|
17
|
-
dst = dst[k];
|
|
18
|
-
src = src[k];
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
return result;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function autoSelect(rel: RelationTypes.RelationConfig, key: string): [string[] | undefined, boolean] {
|
|
26
|
-
const select = Array.isArray(rel.select) ? [...rel.select] : undefined;
|
|
27
|
-
const shouldDelete = select && !select.includes(key);
|
|
28
|
-
if (shouldDelete) select.push(key);
|
|
29
|
-
return [select, shouldDelete];
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function convertSearchObjToSearchArray(obj: Record<string, any>, parentKeys: string[] = []): string[][] {
|
|
33
|
-
return Object.entries(obj).reduce((acc, [key, value]) => {
|
|
34
|
-
const currentPath = [...parentKeys, key];
|
|
35
|
-
|
|
36
|
-
if (!value) {
|
|
37
|
-
return acc;
|
|
38
|
-
} else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
39
|
-
return [...acc, ...convertSearchObjToSearchArray(value, currentPath)];
|
|
40
|
-
} else {
|
|
41
|
-
return [...acc, currentPath];
|
|
42
|
-
}
|
|
43
|
-
}, []);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
async function processRelations(
|
|
47
|
-
dbs: RelationTypes.DBS,
|
|
48
|
-
cfg: RelationTypes.Relation,
|
|
49
|
-
data: any,
|
|
50
|
-
parentList: any[] | null = null
|
|
51
|
-
) {
|
|
52
|
-
if (!data && !parentList) return;
|
|
53
|
-
|
|
54
|
-
const batchMode = Array.isArray(parentList);
|
|
55
|
-
const targets = batchMode ? parentList : [data];
|
|
56
|
-
|
|
57
|
-
for (const key in cfg) {
|
|
58
|
-
if (!cfg.hasOwnProperty(key)) continue;
|
|
59
|
-
const rel = cfg[key];
|
|
60
|
-
const {
|
|
61
|
-
pk = "_id",
|
|
62
|
-
fk = "_id",
|
|
63
|
-
type = "1",
|
|
64
|
-
path,
|
|
65
|
-
as = key,
|
|
66
|
-
select,
|
|
67
|
-
findOpts = {},
|
|
68
|
-
through
|
|
69
|
-
} = rel;
|
|
70
|
-
|
|
71
|
-
const [dbKey, coll] = path;
|
|
72
|
-
const db = dbs[dbKey];
|
|
73
|
-
|
|
74
|
-
if (type === "1") {
|
|
75
|
-
const keys = [...new Set(targets.map(i => i[pk]))];
|
|
76
|
-
const [selectSafe, deleteSelect] = autoSelect(rel, fk);
|
|
77
|
-
const results = await db.find(coll, { $in: { [fk]: keys } }, {}, {}, { select: selectSafe });
|
|
78
|
-
|
|
79
|
-
const map = new Map(results.map(row => [row[fk], row]));
|
|
80
|
-
|
|
81
|
-
for (const item of targets) {
|
|
82
|
-
const result = map.get(item[pk]) || null;
|
|
83
|
-
if (result && rel.relations) {
|
|
84
|
-
await processRelations(dbs, rel.relations, result);
|
|
85
|
-
}
|
|
86
|
-
if (deleteSelect && result) delete result[fk];
|
|
87
|
-
item[as] = result;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
} else if (type === "11") {
|
|
91
|
-
const cache = new Map<string, any>();
|
|
92
|
-
const [selectSafe, deleteSelect] = autoSelect(rel, fk);
|
|
93
|
-
|
|
94
|
-
for (const item of targets) {
|
|
95
|
-
const id = item[pk];
|
|
96
|
-
if (!cache.has(id)) {
|
|
97
|
-
cache.set(id, await db.findOne(coll, { [fk]: id }, {}, { select: selectSafe }));
|
|
98
|
-
}
|
|
99
|
-
const result = cache.get(id) || null;
|
|
100
|
-
if (result && rel.relations) {
|
|
101
|
-
await processRelations(dbs, rel.relations, result);
|
|
102
|
-
}
|
|
103
|
-
if (deleteSelect && result) delete result[fk];
|
|
104
|
-
item[as] = result;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
} else if (type === "1n") {
|
|
108
|
-
const ids = targets.map(i => i[pk]);
|
|
109
|
-
const [selectSafe, deleteSelect] = autoSelect(rel, fk);
|
|
110
|
-
const results = await db.find(coll, { $in: { [fk]: ids } }, {}, findOpts || {}, { select: selectSafe });
|
|
111
|
-
|
|
112
|
-
const grouped = results.reduce((acc, row) => {
|
|
113
|
-
const id = row[fk];
|
|
114
|
-
(acc[id] ||= []).push(row);
|
|
115
|
-
return acc;
|
|
116
|
-
}, {} as Record<string, any[]>);
|
|
117
|
-
|
|
118
|
-
for (const item of targets) {
|
|
119
|
-
item[as] = grouped[item[pk]] || [];
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
if (rel.relations) {
|
|
123
|
-
await Promise.all(results.map(row => processRelations(dbs, rel.relations!, row)));
|
|
124
|
-
}
|
|
125
|
-
if (deleteSelect) for (const r of results) delete r[fk];
|
|
126
|
-
|
|
127
|
-
} else if (type === "nm") {
|
|
128
|
-
if (!through || !through.table || !through.pk || !through.fk) {
|
|
129
|
-
throw new Error(`Relation type "nm" requires a defined 'through' in '${key}'`);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
for (const item of targets) {
|
|
133
|
-
const pivotDb = dbs[through.db || dbKey];
|
|
134
|
-
const pivots = await pivotDb.find(through.table, { [through.pk]: item[pk] });
|
|
135
|
-
const ids = pivots.map(p => p[through.fk]);
|
|
136
|
-
const related = await db.find(coll, { $in: { [fk]: ids } }, {}, {}, { select });
|
|
137
|
-
item[as] = related;
|
|
138
|
-
|
|
139
|
-
if (rel.relations) {
|
|
140
|
-
await Promise.all(related.map(row => processRelations(dbs, rel.relations!, row)));
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
} else {
|
|
145
|
-
throw new Error(`Unknown relation type: ${type}`);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
class Relation {
|
|
151
|
-
constructor(public dbs: RelationTypes.DBS) { }
|
|
152
|
-
|
|
153
|
-
async findOne(
|
|
154
|
-
path: RelationTypes.Path,
|
|
155
|
-
search: Search,
|
|
156
|
-
relations: RelationTypes.Relation,
|
|
157
|
-
select?: string[][] | Record<string, any>
|
|
158
|
-
) {
|
|
159
|
-
const [dbKey, coll] = path;
|
|
160
|
-
const db = this.dbs[dbKey];
|
|
161
|
-
const data = await db.findOne(coll, search);
|
|
162
|
-
if (!data) return null;
|
|
163
|
-
|
|
164
|
-
if (typeof select === "object" && !Array.isArray(select)) {
|
|
165
|
-
select = convertSearchObjToSearchArray(select);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
await processRelations(this.dbs, relations, data);
|
|
169
|
-
return select ? pickByPath(data, select as string[][]) : data;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
async find(
|
|
173
|
-
path: RelationTypes.Path,
|
|
174
|
-
search: Search,
|
|
175
|
-
relations: RelationTypes.Relation,
|
|
176
|
-
select?: string[][] | Record<string, any>,
|
|
177
|
-
findOpts: DbFindOpts = {}
|
|
178
|
-
) {
|
|
179
|
-
const [dbKey, coll] = path;
|
|
180
|
-
const db = this.dbs[dbKey];
|
|
181
|
-
const data = await db.find(coll, search, {}, findOpts);
|
|
182
|
-
if (relations) await processRelations(this.dbs, relations, null, data);
|
|
183
|
-
|
|
184
|
-
if (typeof select === "object" && !Array.isArray(select)) {
|
|
185
|
-
select = convertSearchObjToSearchArray(select);
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
return select ? data.map(d => pickByPath(d, select as string[][])) : data;
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
export default Relation;
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { VQuery } from "../types/query";
|
|
2
|
-
|
|
3
|
-
function assignDataPush(data: any) {
|
|
4
|
-
if (typeof data !== "object" || Array.isArray(data)) return;
|
|
5
|
-
const obj = {};
|
|
6
|
-
for (const key of Object.keys(data)) {
|
|
7
|
-
if (key.startsWith("$")) {
|
|
8
|
-
Object.keys(data[key]).forEach((k) => {
|
|
9
|
-
obj[k] = data[key][k];
|
|
10
|
-
})
|
|
11
|
-
} else
|
|
12
|
-
obj[key] = data[key];
|
|
13
|
-
}
|
|
14
|
-
return obj;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function setDataUsingUpdateOneOrAdd(query: VQuery) {
|
|
18
|
-
query.data = Object.assign(
|
|
19
|
-
{},
|
|
20
|
-
assignDataPush(query.search),
|
|
21
|
-
assignDataPush(query.updater),
|
|
22
|
-
assignDataPush(query.add_arg)
|
|
23
|
-
);
|
|
24
|
-
}
|