twin-db 1.2.0 → 2.0.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.
- package/README.md +66 -18
- package/dist/index.cjs +402 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +80 -0
- package/dist/index.d.ts +80 -2
- package/dist/index.js +362 -2
- package/dist/index.js.map +1 -0
- package/package.json +22 -4
- package/dist/structures/database.d.ts +0 -18
- package/dist/structures/database.js +0 -133
package/README.md
CHANGED
|
@@ -1,19 +1,63 @@
|
|
|
1
1
|
### Before All
|
|
2
|
-
Make sure you're using `"type": "module"` in package.json.<br>
|
|
3
2
|
Make sure to pass just values that JSON accepts, if not, the values will be changed to `null`.
|
|
3
|
+
|
|
4
4
|
# How to Use?
|
|
5
5
|
To create a new database make the following step:
|
|
6
6
|
```js
|
|
7
|
-
import TwinDB from 'twin-db';
|
|
8
|
-
const database = new TwinDB('
|
|
7
|
+
import { TwinDB } from 'twin-db';
|
|
8
|
+
const database = new TwinDB('database/twin');
|
|
9
|
+
```
|
|
10
|
+
or
|
|
11
|
+
```js
|
|
12
|
+
const { TwinDB } = require('twin-db');
|
|
13
|
+
const database = new TwinDB('database/twin');
|
|
9
14
|
```
|
|
10
15
|
And your database is done.
|
|
11
16
|
### You can make various databases too:
|
|
12
17
|
```js
|
|
13
|
-
import TwinDB from 'twin-db';
|
|
14
|
-
const database = new TwinDB('db');
|
|
15
|
-
const coolDatabase = new TwinDB('cool');
|
|
18
|
+
import { TwinDB } from 'twin-db';
|
|
19
|
+
const database = new TwinDB('database/db');
|
|
20
|
+
const coolDatabase = new TwinDB('database/cool');
|
|
21
|
+
```
|
|
22
|
+
> The first argument is a file **path** — folders in it are created automatically if they don't exist. If you don't pass one, it defaults to `database/twin`.
|
|
23
|
+
|
|
24
|
+
# Storages
|
|
25
|
+
By default, `TwinDB` saves your data in a local `.json` file (`JSONStorage`). If you'd rather store it in a local SQLite database, pass `SqliteStorage` in the options:
|
|
26
|
+
```js
|
|
27
|
+
import { TwinDB, SqliteStorage } from 'twin-db';
|
|
28
|
+
|
|
29
|
+
const database = new TwinDB('database/db', { storage: SqliteStorage });
|
|
30
|
+
```
|
|
31
|
+
`SqliteStorage` also accepts an optional `table` and `key`, in case you want more than one database sharing the same `.db` file:
|
|
32
|
+
```js
|
|
33
|
+
const database = new TwinDB('database/db', {
|
|
34
|
+
storage: SqliteStorage,
|
|
35
|
+
table: 'users', // defaults to "twin"
|
|
36
|
+
key: 'main', // defaults to "data"
|
|
37
|
+
});
|
|
16
38
|
```
|
|
39
|
+
Both storages implement the same interface, so switching between them doesn't change any of the methods in **Database Methods**.
|
|
40
|
+
|
|
41
|
+
# TwinMongoDB
|
|
42
|
+
If you'd rather store your data in MongoDB instead of locally, use `TwinMongoDB`. It shares the exact same methods as `TwinDB` (`set`, `get`, `delete`, `sum`, `sub`, `concat`, `push`, `pull`, all with the same `fetch` parameter), the only difference is how you create it and that every method is asynchronous:
|
|
43
|
+
```js
|
|
44
|
+
import { TwinMongoDB } from 'twin-db';
|
|
45
|
+
|
|
46
|
+
const database = new TwinMongoDB('mongodb://localhost:27017/mydb', 'myCollection', 'myId');
|
|
47
|
+
|
|
48
|
+
await database.set('name', 'De');
|
|
49
|
+
const name = await database.get('name');
|
|
50
|
+
await database.push('hobbies', ['sleep'], true);
|
|
51
|
+
```
|
|
52
|
+
- `connectionURI` (required) — your MongoDB connection string.
|
|
53
|
+
- `modelName` (optional) — the collection name, defaults to `"twin"`.
|
|
54
|
+
- `id` (optional) — the document `_id` used to store your data, defaults to `"data"`. Useful if you want multiple independent databases inside the same collection.
|
|
55
|
+
|
|
56
|
+
When you're done with it (e.g. before your process exits), make sure to close the connection so it doesn't hang:
|
|
57
|
+
```js
|
|
58
|
+
await database.close();
|
|
59
|
+
```
|
|
60
|
+
|
|
17
61
|
# Database Methods
|
|
18
62
|
Now we going to explain you the database methods.<br>
|
|
19
63
|
Imagine the following data from a random database:
|
|
@@ -43,18 +87,18 @@ Get a value from a given path.
|
|
|
43
87
|
```js
|
|
44
88
|
database.get('surname'); // returns "Costa".
|
|
45
89
|
```
|
|
46
|
-
### 3. Delete Method
|
|
90
|
+
### 3. Delete/Remove Method
|
|
47
91
|
Deletes a value from data.
|
|
48
92
|
```js
|
|
49
93
|
database.delete('cool') // now the cool value no longer exists.
|
|
50
94
|
database.delete('address.country') // now the country no longer exists too.
|
|
51
95
|
```
|
|
52
|
-
### 4. Sum Method
|
|
96
|
+
### 4. Sum/Add Method
|
|
53
97
|
Sum the current value of the given path with the given value.
|
|
54
98
|
```js
|
|
55
99
|
database.sum('age', 30); // now the age is 80.
|
|
56
100
|
```
|
|
57
|
-
### 5. Sub Method
|
|
101
|
+
### 5. Sub/Subtract Method
|
|
58
102
|
Subtract the current value of the given path with the given value.
|
|
59
103
|
```js
|
|
60
104
|
database.sub('age', 10); // now the age is 70.
|
|
@@ -65,13 +109,14 @@ Concatenate the current value of the given path with the given value.
|
|
|
65
109
|
database.concat('address.city', ' know'); // now the city is "I dont know".
|
|
66
110
|
```
|
|
67
111
|
### 7. Push Method
|
|
68
|
-
Push the given values into the current value array.
|
|
112
|
+
Push the given values into the current value array. **The values must be passed as an array**, even if it's just one value.
|
|
69
113
|
```js
|
|
70
|
-
database.push('hobbies', 'sleep', 'valorant'); // now the hobbies is ["cs", "pizza", "sleep", "valorant"].
|
|
114
|
+
database.push('hobbies', ['sleep', 'valorant']); // now the hobbies is ["cs", "pizza", "sleep", "valorant"].
|
|
71
115
|
```
|
|
72
116
|
### 8. Pull Method
|
|
117
|
+
Removes the given values from the current value array. **The values must be passed as an array**, even if it's just one value.
|
|
73
118
|
```js
|
|
74
|
-
database.pull('hobbies', 'cs', 'sleep') // now the hobbies is ["pizza", "valorant"].
|
|
119
|
+
database.pull('hobbies', ['cs', 'sleep']) // now the hobbies is ["pizza", "valorant"].
|
|
75
120
|
```
|
|
76
121
|
### Now the data object will looks like that:
|
|
77
122
|
```json
|
|
@@ -86,10 +131,13 @@ database.pull('hobbies', 'cs', 'sleep') // now the hobbies is ["pizza", "valoran
|
|
|
86
131
|
}
|
|
87
132
|
}
|
|
88
133
|
```
|
|
89
|
-
## Updates
|
|
90
|
-
`MM/DD/YYYY`<br>
|
|
91
|
-
04/09/2026 - 1.1.*
|
|
92
|
-
- Now **sum**, **sub** and **push** sets the value to the value you passed in execution when the path does not exists.
|
|
93
134
|
|
|
94
|
-
|
|
95
|
-
-
|
|
135
|
+
## The `fetch` parameter
|
|
136
|
+
Every method above accepts an optional `fetch` boolean as its last parameter (default `false`). When `true`, it re-reads the storage before running the operation and refreshes the cache with it — useful if another process might have written to the same storage since your last read.
|
|
137
|
+
```js
|
|
138
|
+
database.get('name', true);
|
|
139
|
+
database.push('hobbies', ['sleep'], true);
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Updates
|
|
143
|
+
See new updates [here](https://github.com/toddy007/twin-db/releases).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
JSONStorage: () => JSONStorage,
|
|
34
|
+
SqliteStorage: () => SqliteStorage,
|
|
35
|
+
TwinDB: () => TwinDB,
|
|
36
|
+
TwinMongoDB: () => TwinMongoDB
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(index_exports);
|
|
39
|
+
|
|
40
|
+
// src/structures/TwinDB.ts
|
|
41
|
+
var import_lodash = __toESM(require("lodash"), 1);
|
|
42
|
+
|
|
43
|
+
// src/storages/JSONStorage.ts
|
|
44
|
+
var import_node_fs = require("node:fs");
|
|
45
|
+
var JSONStorage = class {
|
|
46
|
+
constructor(path2) {
|
|
47
|
+
if (!path2.endsWith(".json")) path2 += ".json";
|
|
48
|
+
this.path = path2;
|
|
49
|
+
if (!(0, import_node_fs.existsSync)(path2)) (0, import_node_fs.writeFileSync)(path2, "{}", "utf8");
|
|
50
|
+
else {
|
|
51
|
+
const data = (0, import_node_fs.readFileSync)(path2, "utf8");
|
|
52
|
+
let parsedData;
|
|
53
|
+
try {
|
|
54
|
+
parsedData = JSON.parse(data);
|
|
55
|
+
} catch (_) {
|
|
56
|
+
}
|
|
57
|
+
if (!data || !parsedData || typeof parsedData !== "object" || Array.isArray(parsedData))
|
|
58
|
+
(0, import_node_fs.writeFileSync)(path2, "{}", "utf8");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
get() {
|
|
62
|
+
let data;
|
|
63
|
+
try {
|
|
64
|
+
data = (0, import_node_fs.readFileSync)(this.path, "utf8");
|
|
65
|
+
} catch (_) {
|
|
66
|
+
}
|
|
67
|
+
let parsedData;
|
|
68
|
+
try {
|
|
69
|
+
if (data) parsedData = JSON.parse(data);
|
|
70
|
+
} catch (_) {
|
|
71
|
+
}
|
|
72
|
+
const checkedData = data && parsedData && typeof parsedData === "object" && !Array.isArray(parsedData);
|
|
73
|
+
if (!checkedData) (0, import_node_fs.writeFileSync)(this.path, "{}", "utf8");
|
|
74
|
+
return checkedData ? parsedData : {};
|
|
75
|
+
}
|
|
76
|
+
set(value) {
|
|
77
|
+
(0, import_node_fs.writeFileSync)(this.path, value, "utf8");
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// src/storages/SqliteStorage.ts
|
|
83
|
+
var import_node_sqlite = require("node:sqlite");
|
|
84
|
+
|
|
85
|
+
// src/utils/vars.ts
|
|
86
|
+
var DEFAULT_KEY = "data";
|
|
87
|
+
var DEFAULT_NAME = "twin";
|
|
88
|
+
var pathErrorMessage = "The path must be a string or you dont provided a path";
|
|
89
|
+
|
|
90
|
+
// src/storages/SqliteStorage.ts
|
|
91
|
+
var SqliteStorage = class {
|
|
92
|
+
constructor(path2, table = DEFAULT_NAME, key = DEFAULT_KEY) {
|
|
93
|
+
if (!table || typeof table !== "string") table = DEFAULT_NAME;
|
|
94
|
+
if (!key || typeof key !== "string") key = DEFAULT_KEY;
|
|
95
|
+
this.table = table;
|
|
96
|
+
this.key = key;
|
|
97
|
+
if (!path2.endsWith(".db")) path2 += ".db";
|
|
98
|
+
this.db = new import_node_sqlite.DatabaseSync(path2);
|
|
99
|
+
this.db.exec(`
|
|
100
|
+
CREATE TABLE IF NOT EXISTS ${table} (
|
|
101
|
+
key TEXT PRIMARY KEY,
|
|
102
|
+
value TEXT
|
|
103
|
+
)
|
|
104
|
+
`);
|
|
105
|
+
}
|
|
106
|
+
set(value) {
|
|
107
|
+
this.db.prepare(
|
|
108
|
+
`INSERT OR REPLACE INTO ${this.table} (key, value) VALUES (?, ?)`
|
|
109
|
+
).run(this.key, value);
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
get() {
|
|
113
|
+
const row = this.db.prepare(`SELECT value FROM ${this.table} WHERE key = ?`).get(this.key);
|
|
114
|
+
return row ? JSON.parse(row.value) : {};
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// src/structures/TwinDB.ts
|
|
119
|
+
var import_node_path = __toESM(require("node:path"), 1);
|
|
120
|
+
var import_node_fs2 = require("node:fs");
|
|
121
|
+
var TwinDB = class {
|
|
122
|
+
constructor(argPath = "database/twin", options = { storage: JSONStorage }) {
|
|
123
|
+
this.remove = this.delete;
|
|
124
|
+
this.add = this.sum;
|
|
125
|
+
this.subtract = this.sub;
|
|
126
|
+
if (!argPath || typeof argPath !== "string")
|
|
127
|
+
throw new Error(pathErrorMessage);
|
|
128
|
+
const solvedPath = import_node_path.default.resolve(process.cwd(), argPath);
|
|
129
|
+
(0, import_node_fs2.mkdirSync)(import_node_path.default.dirname(solvedPath), { recursive: true });
|
|
130
|
+
if (!options || typeof options !== "object" || Array.isArray(options))
|
|
131
|
+
options = { storage: JSONStorage };
|
|
132
|
+
options.storage || (options.storage = JSONStorage);
|
|
133
|
+
if (![JSONStorage, SqliteStorage].includes(options.storage))
|
|
134
|
+
throw new Error("Invalid storage type passed in options");
|
|
135
|
+
this.storage = options.storage === SqliteStorage ? new options.storage(solvedPath, options.table, options.key) : new options.storage(solvedPath);
|
|
136
|
+
this.cache = this.storage.get();
|
|
137
|
+
}
|
|
138
|
+
update(path2, value, fetch = false) {
|
|
139
|
+
if (fetch) this.cache = this.storage.get();
|
|
140
|
+
import_lodash.default.set(this.cache, path2, value);
|
|
141
|
+
this.storage.set(JSON.stringify(this.cache));
|
|
142
|
+
return this.cache;
|
|
143
|
+
}
|
|
144
|
+
set(path2, value, fetch = false) {
|
|
145
|
+
if (!path2 || typeof path2 !== "string")
|
|
146
|
+
throw new Error(pathErrorMessage);
|
|
147
|
+
if (value === void 0)
|
|
148
|
+
throw new Error("You must provide a value to update");
|
|
149
|
+
return this.update(path2, value, fetch);
|
|
150
|
+
}
|
|
151
|
+
get(path2, fetch = false) {
|
|
152
|
+
if (!path2 || typeof path2 !== "string")
|
|
153
|
+
throw new Error(pathErrorMessage);
|
|
154
|
+
if (fetch) this.cache = this.storage.get();
|
|
155
|
+
return import_lodash.default.get(this.cache, path2, null);
|
|
156
|
+
}
|
|
157
|
+
delete(path2, fetch = false) {
|
|
158
|
+
if (!path2 || typeof path2 !== "string")
|
|
159
|
+
throw new Error(pathErrorMessage);
|
|
160
|
+
if (fetch) this.cache = this.storage.get();
|
|
161
|
+
const pathExists = this.get(path2);
|
|
162
|
+
if (pathExists === null)
|
|
163
|
+
throw new Error("The path does not exists or its value is null");
|
|
164
|
+
return this.update(path2, null);
|
|
165
|
+
}
|
|
166
|
+
sumOrSub(path2, value, type, fetch = false) {
|
|
167
|
+
if (!path2 || typeof path2 !== "string")
|
|
168
|
+
throw new Error(pathErrorMessage);
|
|
169
|
+
if (!type || !["sum", "sub"].includes(type))
|
|
170
|
+
throw new Error('The type must be "sum" or "sub"');
|
|
171
|
+
const isSum = type === "sum";
|
|
172
|
+
if (!value || typeof value !== "number")
|
|
173
|
+
throw new Error(
|
|
174
|
+
`The value to ${isSum ? "sum" : "sub"} must be a number`
|
|
175
|
+
);
|
|
176
|
+
if (fetch) this.cache = this.storage.get();
|
|
177
|
+
let currentValue = this.get(path2) || 0;
|
|
178
|
+
if (typeof currentValue !== "number") currentValue = 0;
|
|
179
|
+
return this.update(
|
|
180
|
+
path2,
|
|
181
|
+
isSum ? currentValue + value : currentValue - value
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
sum(path2, value, fetch = false) {
|
|
185
|
+
return this.sumOrSub(path2, value, "sum", fetch);
|
|
186
|
+
}
|
|
187
|
+
sub(path2, value, fetch = false) {
|
|
188
|
+
return this.sumOrSub(path2, value, "sub", fetch);
|
|
189
|
+
}
|
|
190
|
+
concat(path2, value, fetch = false) {
|
|
191
|
+
if (!path2 || typeof path2 !== "string")
|
|
192
|
+
throw new Error(pathErrorMessage);
|
|
193
|
+
if (!value || typeof value !== "string")
|
|
194
|
+
throw new Error("You must provide a string value to update");
|
|
195
|
+
if (fetch) this.cache = this.storage.get();
|
|
196
|
+
const currentValue = this.get(path2);
|
|
197
|
+
if (typeof currentValue !== "string")
|
|
198
|
+
throw new Error(
|
|
199
|
+
"The value to concat is not a string or the path does not exists"
|
|
200
|
+
);
|
|
201
|
+
return this.update(path2, currentValue + value);
|
|
202
|
+
}
|
|
203
|
+
push(path2, values, fetch = false) {
|
|
204
|
+
if (!path2 || typeof path2 !== "string")
|
|
205
|
+
throw new Error(pathErrorMessage);
|
|
206
|
+
if (!values || values.length === 0)
|
|
207
|
+
throw new Error("You must provide a value to update");
|
|
208
|
+
if (fetch) this.cache = this.storage.get();
|
|
209
|
+
let currentValue = this.get(path2) || [];
|
|
210
|
+
if (!Array.isArray(currentValue)) currentValue = [];
|
|
211
|
+
currentValue.push(...values);
|
|
212
|
+
return this.update(path2, currentValue);
|
|
213
|
+
}
|
|
214
|
+
pull(path2, values, fetch = false) {
|
|
215
|
+
if (!path2 || typeof path2 !== "string")
|
|
216
|
+
throw new Error(pathErrorMessage);
|
|
217
|
+
if (!values || values.length === 0)
|
|
218
|
+
throw new Error("You must provide a value to update");
|
|
219
|
+
if (fetch) this.cache = this.storage.get();
|
|
220
|
+
const currentValue = this.get(path2);
|
|
221
|
+
if (!Array.isArray(currentValue))
|
|
222
|
+
throw new Error(
|
|
223
|
+
"The current value of this path is not an array or the path does not exists"
|
|
224
|
+
);
|
|
225
|
+
for (const value of values) {
|
|
226
|
+
const index = currentValue.indexOf(value);
|
|
227
|
+
if (index < 0) continue;
|
|
228
|
+
currentValue.splice(index, 1);
|
|
229
|
+
}
|
|
230
|
+
return this.update(path2, currentValue);
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
// src/structures/TwinMongoDB.ts
|
|
235
|
+
var import_lodash2 = __toESM(require("lodash"), 1);
|
|
236
|
+
var import_mongodb = require("mongodb");
|
|
237
|
+
var TwinMongoDB = class {
|
|
238
|
+
constructor(connectionURI, modelName = DEFAULT_NAME, id = DEFAULT_KEY) {
|
|
239
|
+
this.remove = this.delete;
|
|
240
|
+
this.add = this.sum;
|
|
241
|
+
this.subtract = this.sub;
|
|
242
|
+
if (!modelName || typeof modelName !== "string")
|
|
243
|
+
modelName = DEFAULT_NAME;
|
|
244
|
+
if (!id || typeof id !== "string") id = DEFAULT_KEY;
|
|
245
|
+
this.client = new import_mongodb.MongoClient(connectionURI);
|
|
246
|
+
this.cache = {};
|
|
247
|
+
this.id = id;
|
|
248
|
+
this.initPromise = this.init(modelName);
|
|
249
|
+
}
|
|
250
|
+
async init(modelName) {
|
|
251
|
+
await this.client.connect();
|
|
252
|
+
this.collection = this.client.db().collection(modelName);
|
|
253
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
254
|
+
if (!data) {
|
|
255
|
+
const created = { _id: this.id, data: {} };
|
|
256
|
+
await this.collection.insertOne(created);
|
|
257
|
+
this.cache = created.data;
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
this.cache = data.data;
|
|
261
|
+
}
|
|
262
|
+
async close() {
|
|
263
|
+
await this.client.close();
|
|
264
|
+
}
|
|
265
|
+
async ready() {
|
|
266
|
+
await this.initPromise;
|
|
267
|
+
}
|
|
268
|
+
async update(path2, value, fetch = false) {
|
|
269
|
+
await this.ready();
|
|
270
|
+
if (fetch) {
|
|
271
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
272
|
+
this.cache = data ? data.data : {};
|
|
273
|
+
}
|
|
274
|
+
import_lodash2.default.set(this.cache, path2, value);
|
|
275
|
+
await this.collection.updateOne(
|
|
276
|
+
{ _id: this.id },
|
|
277
|
+
{ $set: { data: this.cache } },
|
|
278
|
+
{ upsert: true }
|
|
279
|
+
);
|
|
280
|
+
return this.cache;
|
|
281
|
+
}
|
|
282
|
+
async set(path2, value, fetch = false) {
|
|
283
|
+
if (!path2 || typeof path2 !== "string")
|
|
284
|
+
throw new Error(pathErrorMessage);
|
|
285
|
+
if (value === void 0)
|
|
286
|
+
throw new Error("You must provide a value to update");
|
|
287
|
+
return this.update(path2, value, fetch);
|
|
288
|
+
}
|
|
289
|
+
async get(path2, fetch = false) {
|
|
290
|
+
if (!path2 || typeof path2 !== "string")
|
|
291
|
+
throw new Error(pathErrorMessage);
|
|
292
|
+
await this.ready();
|
|
293
|
+
if (fetch) {
|
|
294
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
295
|
+
this.cache = data ? data.data : {};
|
|
296
|
+
}
|
|
297
|
+
return import_lodash2.default.get(this.cache, path2, null);
|
|
298
|
+
}
|
|
299
|
+
async delete(path2, fetch = false) {
|
|
300
|
+
if (!path2 || typeof path2 !== "string")
|
|
301
|
+
throw new Error(pathErrorMessage);
|
|
302
|
+
await this.ready();
|
|
303
|
+
if (fetch) {
|
|
304
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
305
|
+
this.cache = data ? data.data : {};
|
|
306
|
+
}
|
|
307
|
+
const pathExists = await this.get(path2);
|
|
308
|
+
if (pathExists === null)
|
|
309
|
+
throw new Error("The path does not exists or its value is null");
|
|
310
|
+
return this.update(path2, null);
|
|
311
|
+
}
|
|
312
|
+
async sumOrSub(path2, value, type, fetch = false) {
|
|
313
|
+
if (!path2 || typeof path2 !== "string")
|
|
314
|
+
throw new Error(pathErrorMessage);
|
|
315
|
+
if (!type || !["sum", "sub"].includes(type))
|
|
316
|
+
throw new Error('The type must be "sum" or "sub"');
|
|
317
|
+
const isSum = type === "sum";
|
|
318
|
+
if (!value || typeof value !== "number")
|
|
319
|
+
throw new Error(
|
|
320
|
+
`The value to ${isSum ? "sum" : "sub"} must be a number`
|
|
321
|
+
);
|
|
322
|
+
await this.ready();
|
|
323
|
+
if (fetch) {
|
|
324
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
325
|
+
this.cache = data ? data.data : {};
|
|
326
|
+
}
|
|
327
|
+
let currentValue = await this.get(path2) || 0;
|
|
328
|
+
if (typeof currentValue !== "number") currentValue = 0;
|
|
329
|
+
return this.update(
|
|
330
|
+
path2,
|
|
331
|
+
isSum ? currentValue + value : currentValue - value
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
async sum(path2, value, fetch = false) {
|
|
335
|
+
return this.sumOrSub(path2, value, "sum", fetch);
|
|
336
|
+
}
|
|
337
|
+
async sub(path2, value, fetch = false) {
|
|
338
|
+
return this.sumOrSub(path2, value, "sub", fetch);
|
|
339
|
+
}
|
|
340
|
+
async concat(path2, value, fetch = false) {
|
|
341
|
+
if (!path2 || typeof path2 !== "string")
|
|
342
|
+
throw new Error(pathErrorMessage);
|
|
343
|
+
if (!value || typeof value !== "string")
|
|
344
|
+
throw new Error("You must provide a string value to update");
|
|
345
|
+
await this.ready();
|
|
346
|
+
if (fetch) {
|
|
347
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
348
|
+
this.cache = data ? data.data : {};
|
|
349
|
+
}
|
|
350
|
+
const currentValue = await this.get(path2);
|
|
351
|
+
if (typeof currentValue !== "string")
|
|
352
|
+
throw new Error(
|
|
353
|
+
"The value to concat is not a string or the path does not exists"
|
|
354
|
+
);
|
|
355
|
+
return this.update(path2, currentValue + value);
|
|
356
|
+
}
|
|
357
|
+
async push(path2, values, fetch = false) {
|
|
358
|
+
if (!path2 || typeof path2 !== "string")
|
|
359
|
+
throw new Error(pathErrorMessage);
|
|
360
|
+
if (!values || values.length === 0)
|
|
361
|
+
throw new Error("You must provide a value to update");
|
|
362
|
+
await this.ready();
|
|
363
|
+
if (fetch) {
|
|
364
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
365
|
+
this.cache = data ? data.data : {};
|
|
366
|
+
}
|
|
367
|
+
let currentValue = await this.get(path2) || [];
|
|
368
|
+
if (!Array.isArray(currentValue)) currentValue = [];
|
|
369
|
+
currentValue.push(...values);
|
|
370
|
+
return this.update(path2, currentValue);
|
|
371
|
+
}
|
|
372
|
+
async pull(path2, values, fetch = false) {
|
|
373
|
+
if (!path2 || typeof path2 !== "string")
|
|
374
|
+
throw new Error(pathErrorMessage);
|
|
375
|
+
if (!values || values.length === 0)
|
|
376
|
+
throw new Error("You must provide a value to update");
|
|
377
|
+
await this.ready();
|
|
378
|
+
if (fetch) {
|
|
379
|
+
const data = await this.collection.findOne({ _id: this.id });
|
|
380
|
+
this.cache = data ? data.data : {};
|
|
381
|
+
}
|
|
382
|
+
const currentValue = await this.get(path2);
|
|
383
|
+
if (!Array.isArray(currentValue))
|
|
384
|
+
throw new Error(
|
|
385
|
+
"The current value of this path is not an array or the path does not exists"
|
|
386
|
+
);
|
|
387
|
+
for (const value of values) {
|
|
388
|
+
const index = currentValue.indexOf(value);
|
|
389
|
+
if (index < 0) continue;
|
|
390
|
+
currentValue.splice(index, 1);
|
|
391
|
+
}
|
|
392
|
+
return this.update(path2, currentValue);
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
396
|
+
0 && (module.exports = {
|
|
397
|
+
JSONStorage,
|
|
398
|
+
SqliteStorage,
|
|
399
|
+
TwinDB,
|
|
400
|
+
TwinMongoDB
|
|
401
|
+
});
|
|
402
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/structures/TwinDB.ts","../src/storages/JSONStorage.ts","../src/storages/SqliteStorage.ts","../src/utils/vars.ts","../src/structures/TwinMongoDB.ts"],"sourcesContent":["export { TwinDB } from './structures/TwinDB.js';\nexport { TwinMongoDB } from './structures/TwinMongoDB.js';\n\nexport { JSONStorage } from './storages/JSONStorage.js';\nexport { SqliteStorage } from './storages/SqliteStorage.js';\n","import lodash from 'lodash';\nimport {\n SumOrSub,\n TwinDBOptions,\n StorageInstanceType,\n} from '../types/global.js';\nimport { JSONStorage } from '../storages/JSONStorage.js';\nimport { SqliteStorage } from '../storages/SqliteStorage.js';\nimport path from 'node:path';\nimport { mkdirSync } from 'node:fs';\nimport { pathErrorMessage } from '../utils/vars.js';\n\nexport class TwinDB {\n public cache: Record<string, unknown>;\n private storage: StorageInstanceType;\n\n public constructor(\n argPath: string = 'database/twin',\n options: TwinDBOptions = { storage: JSONStorage },\n ) {\n if (!argPath || typeof argPath !== 'string')\n throw new Error(pathErrorMessage);\n\n const solvedPath = path.resolve(process.cwd(), argPath);\n mkdirSync(path.dirname(solvedPath), { recursive: true });\n\n if (!options || typeof options !== 'object' || Array.isArray(options))\n options = { storage: JSONStorage };\n\n options.storage ||= JSONStorage;\n\n if (![JSONStorage, SqliteStorage].includes(options.storage))\n throw new Error('Invalid storage type passed in options');\n\n this.storage =\n options.storage === SqliteStorage\n // @ts-expect-error - table and key exists here\n ? new options.storage(solvedPath, options.table, options.key)\n : new options.storage(solvedPath);\n\n this.cache = this.storage.get();\n }\n\n private update(\n path: string /*user.info.name*/,\n value: unknown,\n fetch: boolean = false,\n ) {\n if (fetch) this.cache = this.storage.get();\n\n lodash.set(this.cache, path, value);\n\n this.storage.set(JSON.stringify(this.cache));\n\n return this.cache;\n }\n\n public set(path: string, value: unknown, fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (value === undefined)\n throw new Error('You must provide a value to update');\n\n return this.update(path, value, fetch);\n }\n\n public get(path: string, fetch: boolean = false): unknown | null {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n\n if (fetch) this.cache = this.storage.get();\n\n return lodash.get(this.cache, path, null);\n }\n\n public delete(path: string, fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n\n if (fetch) this.cache = this.storage.get();\n\n const pathExists = this.get(path);\n if (pathExists === null)\n throw new Error('The path does not exists or its value is null');\n\n return this.update(path, null);\n }\n\n public remove = this.delete;\n\n private sumOrSub(\n path: string,\n value: number,\n type: SumOrSub,\n fetch: boolean = false,\n ) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!type || !['sum', 'sub'].includes(type))\n throw new Error('The type must be \"sum\" or \"sub\"');\n const isSum = type === 'sum';\n if (!value || typeof value !== 'number')\n throw new Error(\n `The value to ${isSum ? 'sum' : 'sub'} must be a number`,\n );\n\n if (fetch) this.cache = this.storage.get();\n\n let currentValue = (this.get(path) || 0) as unknown as number;\n if (typeof currentValue !== 'number') currentValue = 0;\n\n return this.update(\n path,\n isSum ? currentValue + value : currentValue - value,\n );\n }\n\n public sum(path: string, value: number, fetch: boolean = false) {\n return this.sumOrSub(path, value, 'sum', fetch);\n }\n\n public add = this.sum;\n\n public sub(path: string, value: number, fetch: boolean = false) {\n return this.sumOrSub(path, value, 'sub', fetch);\n }\n\n public subtract = this.sub;\n\n public concat(path: string, value: string, fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!value || typeof value !== 'string')\n throw new Error('You must provide a string value to update');\n\n if (fetch) this.cache = this.storage.get();\n\n const currentValue = this.get(path);\n if (typeof currentValue !== 'string')\n throw new Error(\n 'The value to concat is not a string or the path does not exists',\n );\n\n return this.update(path, currentValue + value);\n }\n\n public push(path: string, values: unknown[], fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!values || values.length === 0)\n throw new Error('You must provide a value to update');\n\n if (fetch) this.cache = this.storage.get();\n\n let currentValue = (this.get(path) || []) as unknown as unknown[];\n if (!Array.isArray(currentValue)) currentValue = [];\n\n currentValue.push(...values);\n return this.update(path, currentValue);\n }\n\n public pull(path: string, values: unknown[], fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!values || values.length === 0)\n throw new Error('You must provide a value to update');\n\n if (fetch) this.cache = this.storage.get();\n\n const currentValue = this.get(path);\n if (!Array.isArray(currentValue))\n throw new Error(\n 'The current value of this path is not an array or the path does not exists',\n );\n\n for (const value of values) {\n const index = currentValue.indexOf(value);\n if (index < 0) continue;\n\n currentValue.splice(index, 1);\n }\n\n return this.update(path, currentValue);\n }\n}\n","import { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { Storage } from '../types/Storage.js';\n\nexport class JSONStorage implements Storage {\n public readonly path: string;\n\n public constructor(path: string) {\n if (!path.endsWith('.json')) path += '.json';\n this.path = path;\n\n if (!existsSync(path)) writeFileSync(path, '{}', 'utf8');\n else {\n const data = readFileSync(path, 'utf8');\n let parsedData;\n try {\n parsedData = JSON.parse(data);\n } catch (_) {}\n\n if (\n !data ||\n !parsedData ||\n typeof parsedData !== 'object' ||\n Array.isArray(parsedData)\n )\n writeFileSync(path, '{}', 'utf8');\n }\n }\n\n public get() {\n let data;\n try {\n data = readFileSync(this.path, 'utf8');\n } catch (_) {}\n\n let parsedData;\n try {\n if (data) parsedData = JSON.parse(data);\n } catch (_) {}\n\n const checkedData =\n data &&\n parsedData &&\n typeof parsedData === 'object' &&\n !Array.isArray(parsedData);\n if (!checkedData) writeFileSync(this.path, '{}', 'utf8');\n\n return checkedData ? parsedData : {};\n }\n\n public set(value: string) {\n writeFileSync(this.path, value, 'utf8');\n\n return true;\n }\n}\n","import { Storage } from '../types/Storage.js';\nimport { DatabaseSync } from 'node:sqlite';\nimport { DEFAULT_KEY, DEFAULT_NAME } from '../utils/vars.js';\n\nexport class SqliteStorage implements Storage {\n private readonly db: DatabaseSync;\n private readonly table: string;\n private readonly key: string;\n\n public constructor(\n path: string,\n table: string = DEFAULT_NAME,\n key: string = DEFAULT_KEY,\n ) {\n if (!table || typeof table !== 'string') table = DEFAULT_NAME;\n if (!key || typeof key !== 'string') key = DEFAULT_KEY;\n\n this.table = table;\n this.key = key;\n\n if (!path.endsWith('.db')) path += '.db';\n this.db = new DatabaseSync(path);\n\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS ${table} (\n key TEXT PRIMARY KEY,\n value TEXT\n )\n `);\n }\n\n public set(value: string /*json strringfyed value*/) {\n this.db\n .prepare(\n `INSERT OR REPLACE INTO ${this.table} (key, value) VALUES (?, ?)`,\n )\n .run(this.key, value);\n\n return true;\n }\n\n public get() {\n const row = this.db\n .prepare(`SELECT value FROM ${this.table} WHERE key = ?`)\n .get(this.key) as unknown as { value: string } | undefined;\n\n return row ? JSON.parse(row.value) : {};\n }\n}\n","export const DEFAULT_KEY = 'data';\n\nexport const DEFAULT_NAME = 'twin';\n\nexport const pathErrorMessage =\n 'The path must be a string or you dont provided a path';\n","import lodash from 'lodash';\nimport { MongoClient, Collection } from 'mongodb';\nimport { SumOrSub, DefaultSchemaType } from '../types/global.js';\nimport { DEFAULT_KEY, DEFAULT_NAME, pathErrorMessage } from '../utils/vars.js';\n\nexport class TwinMongoDB {\n private readonly client: MongoClient;\n private collection!: Collection<DefaultSchemaType>;\n public cache: Record<string, unknown>;\n private initPromise: Promise<void>;\n private readonly id: string;\n\n public constructor(\n connectionURI: string,\n modelName: string = DEFAULT_NAME,\n id: string = DEFAULT_KEY,\n ) {\n if (!modelName || typeof modelName !== 'string')\n modelName = DEFAULT_NAME;\n if (!id || typeof id !== 'string') id = DEFAULT_KEY;\n\n this.client = new MongoClient(connectionURI);\n this.cache = {};\n this.id = id;\n\n this.initPromise = this.init(modelName);\n }\n\n private async init(modelName: string) {\n await this.client.connect();\n\n this.collection = this.client\n .db()\n .collection<DefaultSchemaType>(modelName);\n\n const data = await this.collection.findOne({ _id: this.id });\n\n if (!data) {\n const created: DefaultSchemaType = { _id: this.id, data: {} };\n await this.collection.insertOne(created);\n\n this.cache = created.data;\n return;\n }\n\n this.cache = data.data;\n }\n\n public async close() {\n await this.client.close();\n }\n\n private async ready() {\n await this.initPromise;\n }\n\n private async update(path: string, value: unknown, fetch: boolean = false) {\n await this.ready();\n if (fetch) {\n const data = await this.collection.findOne({ _id: this.id });\n this.cache = data ? data.data : {};\n }\n\n lodash.set(this.cache, path, value);\n\n await this.collection.updateOne(\n { _id: this.id },\n { $set: { data: this.cache } },\n { upsert: true },\n );\n\n return this.cache;\n }\n\n public async set(path: string, value: unknown, fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (value === undefined)\n throw new Error('You must provide a value to update');\n\n return this.update(path, value, fetch);\n }\n\n public async get(\n path: string,\n fetch: boolean = false,\n ): Promise<unknown | null> {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n\n await this.ready();\n if (fetch) {\n const data = await this.collection.findOne({ _id: this.id });\n this.cache = data ? data.data : {};\n }\n\n return lodash.get(this.cache, path, null);\n }\n\n public async delete(path: string, fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n\n await this.ready();\n if (fetch) {\n const data = await this.collection.findOne({ _id: this.id });\n this.cache = data ? data.data : {};\n }\n\n const pathExists = await this.get(path);\n if (pathExists === null)\n throw new Error('The path does not exists or its value is null');\n\n return this.update(path, null);\n }\n\n public remove = this.delete;\n\n private async sumOrSub(\n path: string,\n value: number,\n type: SumOrSub,\n fetch: boolean = false,\n ) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!type || !['sum', 'sub'].includes(type))\n throw new Error('The type must be \"sum\" or \"sub\"');\n const isSum = type === 'sum';\n if (!value || typeof value !== 'number')\n throw new Error(\n `The value to ${isSum ? 'sum' : 'sub'} must be a number`,\n );\n\n await this.ready();\n if (fetch) {\n const data = await this.collection.findOne({ _id: this.id });\n this.cache = data ? data.data : {};\n }\n\n let currentValue = ((await this.get(path)) || 0) as unknown as number;\n if (typeof currentValue !== 'number') currentValue = 0;\n\n return this.update(\n path,\n isSum ? currentValue + value : currentValue - value,\n );\n }\n\n public async sum(path: string, value: number, fetch: boolean = false) {\n return this.sumOrSub(path, value, 'sum', fetch);\n }\n\n public add = this.sum;\n\n public async sub(path: string, value: number, fetch: boolean = false) {\n return this.sumOrSub(path, value, 'sub', fetch);\n }\n\n public subtract = this.sub;\n\n public async concat(path: string, value: string, fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!value || typeof value !== 'string')\n throw new Error('You must provide a string value to update');\n\n await this.ready();\n if (fetch) {\n const data = await this.collection.findOne({ _id: this.id });\n this.cache = data ? data.data : {};\n }\n\n const currentValue = await this.get(path);\n if (typeof currentValue !== 'string')\n throw new Error(\n 'The value to concat is not a string or the path does not exists',\n );\n\n return this.update(path, currentValue + value);\n }\n\n public async push(path: string, values: unknown[], fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!values || values.length === 0)\n throw new Error('You must provide a value to update');\n\n await this.ready();\n if (fetch) {\n const data = await this.collection.findOne({ _id: this.id });\n this.cache = data ? data.data : {};\n }\n\n let currentValue = ((await this.get(path)) ||\n []) as unknown as unknown[];\n if (!Array.isArray(currentValue)) currentValue = [];\n\n currentValue.push(...values);\n return this.update(path, currentValue);\n }\n\n public async pull(path: string, values: unknown[], fetch: boolean = false) {\n if (!path || typeof path !== 'string')\n throw new Error(pathErrorMessage);\n if (!values || values.length === 0)\n throw new Error('You must provide a value to update');\n\n await this.ready();\n if (fetch) {\n const data = await this.collection.findOne({ _id: this.id });\n this.cache = data ? data.data : {};\n }\n\n const currentValue = await this.get(path);\n if (!Array.isArray(currentValue))\n throw new Error(\n 'The current value of this path is not an array or the path does not exists',\n );\n\n for (const value of values) {\n const index = currentValue.indexOf(value);\n if (index < 0) continue;\n\n currentValue.splice(index, 1);\n }\n\n return this.update(path, currentValue);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAmB;;;ACAnB,qB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,KAAK,GAAG,CAAC;AAC3D,WAAK,QAAQ,OAAO,KAAK,OAAO,CAAC;AAAA,IACrC;AAEA,QAAI,eAAiB,MAAM,KAAK,IAAIA,KAAI,KACpC,CAAC;AACL,QAAI,CAAC,MAAM,QAAQ,YAAY,EAAG,gBAAe,CAAC;AAElD,iBAAa,KAAK,GAAG,MAAM;AAC3B,WAAO,KAAK,OAAOA,OAAM,YAAY;AAAA,EACzC;AAAA,EAEA,MAAa,KAAKA,OAAc,QAAmB,QAAiB,OAAO;AACvE,QAAI,CAACA,SAAQ,OAAOA,UAAS;AACzB,YAAM,IAAI,MAAM,gBAAgB;AACpC,QAAI,CAAC,UAAU,OAAO,WAAW;AAC7B,YAAM,IAAI,MAAM,oCAAoC;AAExD,UAAM,KAAK,MAAM;AACjB,QAAI,OAAO;AACP,YAAM,OAAO,MAAM,KAAK,WAAW,QAAQ,EAAE,KAAK,KAAK,GAAG,CAAC;AAC3D,WAAK,QAAQ,OAAO,KAAK,OAAO,CAAC;AAAA,IACrC;AAEA,UAAM,eAAe,MAAM,KAAK,IAAIA,KAAI;AACxC,QAAI,CAAC,MAAM,QAAQ,YAAY;AAC3B,YAAM,IAAI;AAAA,QACN;AAAA,MACJ;AAEJ,eAAW,SAAS,QAAQ;AACxB,YAAM,QAAQ,aAAa,QAAQ,KAAK;AACxC,UAAI,QAAQ,EAAG;AAEf,mBAAa,OAAO,OAAO,CAAC;AAAA,IAChC;AAEA,WAAO,KAAK,OAAOA,OAAM,YAAY;AAAA,EACzC;AACJ;","names":["path","path","import_node_fs","path","lodash","import_lodash","path","lodash"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
interface Storage {
|
|
2
|
+
get(): object;
|
|
3
|
+
set(value: string): unknown;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
declare class SqliteStorage implements Storage {
|
|
7
|
+
private readonly db;
|
|
8
|
+
private readonly table;
|
|
9
|
+
private readonly key;
|
|
10
|
+
constructor(path: string, table?: string, key?: string);
|
|
11
|
+
set(value: string): boolean;
|
|
12
|
+
get(): object;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
declare class JSONStorage implements Storage {
|
|
16
|
+
readonly path: string;
|
|
17
|
+
constructor(path: string);
|
|
18
|
+
get(): object;
|
|
19
|
+
set(value: string): boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type StorageType = typeof SqliteStorage | typeof JSONStorage;
|
|
23
|
+
interface DefaultOptions {
|
|
24
|
+
storage?: StorageType;
|
|
25
|
+
}
|
|
26
|
+
interface JSONStorageOptions extends DefaultOptions {
|
|
27
|
+
storage?: typeof JSONStorage;
|
|
28
|
+
}
|
|
29
|
+
interface SqliteStorageOptions extends DefaultOptions {
|
|
30
|
+
key?: string;
|
|
31
|
+
table?: string;
|
|
32
|
+
storage: typeof SqliteStorage;
|
|
33
|
+
}
|
|
34
|
+
type TwinDBOptions = JSONStorageOptions | SqliteStorageOptions;
|
|
35
|
+
|
|
36
|
+
declare class TwinDB {
|
|
37
|
+
cache: Record<string, unknown>;
|
|
38
|
+
private storage;
|
|
39
|
+
constructor(argPath?: string, options?: TwinDBOptions);
|
|
40
|
+
private update;
|
|
41
|
+
set(path: string, value: unknown, fetch?: boolean): Record<string, unknown>;
|
|
42
|
+
get(path: string, fetch?: boolean): unknown | null;
|
|
43
|
+
delete(path: string, fetch?: boolean): Record<string, unknown>;
|
|
44
|
+
remove: (path: string, fetch?: boolean) => Record<string, unknown>;
|
|
45
|
+
private sumOrSub;
|
|
46
|
+
sum(path: string, value: number, fetch?: boolean): Record<string, unknown>;
|
|
47
|
+
add: (path: string, value: number, fetch?: boolean) => Record<string, unknown>;
|
|
48
|
+
sub(path: string, value: number, fetch?: boolean): Record<string, unknown>;
|
|
49
|
+
subtract: (path: string, value: number, fetch?: boolean) => Record<string, unknown>;
|
|
50
|
+
concat(path: string, value: string, fetch?: boolean): Record<string, unknown>;
|
|
51
|
+
push(path: string, values: unknown[], fetch?: boolean): Record<string, unknown>;
|
|
52
|
+
pull(path: string, values: unknown[], fetch?: boolean): Record<string, unknown>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
declare class TwinMongoDB {
|
|
56
|
+
private readonly client;
|
|
57
|
+
private collection;
|
|
58
|
+
cache: Record<string, unknown>;
|
|
59
|
+
private initPromise;
|
|
60
|
+
private readonly id;
|
|
61
|
+
constructor(connectionURI: string, modelName?: string, id?: string);
|
|
62
|
+
private init;
|
|
63
|
+
close(): Promise<void>;
|
|
64
|
+
private ready;
|
|
65
|
+
private update;
|
|
66
|
+
set(path: string, value: unknown, fetch?: boolean): Promise<Record<string, unknown>>;
|
|
67
|
+
get(path: string, fetch?: boolean): Promise<unknown | null>;
|
|
68
|
+
delete(path: string, fetch?: boolean): Promise<Record<string, unknown>>;
|
|
69
|
+
remove: (path: string, fetch?: boolean) => Promise<Record<string, unknown>>;
|
|
70
|
+
private sumOrSub;
|
|
71
|
+
sum(path: string, value: number, fetch?: boolean): Promise<Record<string, unknown>>;
|
|
72
|
+
add: (path: string, value: number, fetch?: boolean) => Promise<Record<string, unknown>>;
|
|
73
|
+
sub(path: string, value: number, fetch?: boolean): Promise<Record<string, unknown>>;
|
|
74
|
+
subtract: (path: string, value: number, fetch?: boolean) => Promise<Record<string, unknown>>;
|
|
75
|
+
concat(path: string, value: string, fetch?: boolean): Promise<Record<string, unknown>>;
|
|
76
|
+
push(path: string, values: unknown[], fetch?: boolean): Promise<Record<string, unknown>>;
|
|
77
|
+
pull(path: string, values: unknown[], fetch?: boolean): Promise<Record<string, unknown>>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export { JSONStorage, SqliteStorage, TwinDB, TwinMongoDB };
|