-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.ts
More file actions
307 lines (277 loc) · 9.54 KB
/
table.ts
File metadata and controls
307 lines (277 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { msgpack } from "./deps.ts";
import { Kwik } from "./kwik.ts";
export class KwikTable<T> {
private readonly tableName: string;
private kwik: Kwik;
constructor(kwik: Kwik, tableName: string) {
this.kwik = kwik;
this.tableName = tableName;
this.kwik.tables.set(tableName, this);
}
/** Saves the provided document as a file */
private async saveFile(id: string, data: Partial<T>) {
return await Deno.writeFile(
`${this.kwik.directoryPath}${this.tableName}/${id}.kwik`,
msgpack.encode(data, { extensionCodec: this.kwik.msgpackExtensionCodec }),
);
}
/** Create a document with the provided data */
async create(id: string, data: Partial<T> = {}) {
// Deno doesn't provide any workaround for this.
if (await this.has(id)) {
return this.kwik.error(
`[Kwik: create] Cannot create already existing file file://${this.kwik.directoryPath}${this.tableName}/${id}.kwik`,
);
}
return await this.saveFile(id, data);
}
/** Check if a document exists
* @remarks This method only checks for the existence of the file, and can provoke a race condition. If you can, run the actual operation instead, and catch for an error.
* @returns Whether or not the document exists.
*/
async has(id: string): Promise<boolean> {
try {
const info = await Deno.lstat(
`${this.kwik.directoryPath}${this.tableName}/${id}.kwik`,
);
return info.isFile;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return false;
}
throw err;
}
}
/** Get a document from the table.
* @returns The document data or undefined if it doesn't exist.
*/
async get(id: string): Promise<T | undefined> {
try {
const data = await Deno.readFile(
`${this.kwik.directoryPath}${this.tableName}/${id}.kwik`,
);
return msgpack.decode(data, {
extensionCodec: this.kwik.msgpackExtensionCodec,
}) as T;
} catch (error) {
await this.kwik.error(
`[Kwik: get] Unable to read file file://${this.kwik.directoryPath}${this.tableName}/${id}.kwik`,
error,
);
}
}
/** Get all documents of the table.
* @returns A map of all documents with their corresponding data.
*/
async getAll(): Promise<Map<string, T>> {
const data = new Map<string, T>();
for await (
const file of Deno.readDir(
Deno.realPathSync(`${this.kwik.directoryPath}${this.tableName}`),
)
) {
if (!file.name || !file.isFile) continue;
try {
const name = file.name.substring(0, file.name.lastIndexOf("."));
const decodedData = await this.get(name);
if (decodedData) {
data.set(name, decodedData);
}
} catch (error) {
await this.kwik.error(
`[Kwik: getAll]: Unable to read file ${this.kwik.directoryPath}${this.tableName}/${file.name}`,
error,
);
}
}
return data;
}
/** Get all documents from a table that match a filter */
async findMany(
filter: Record<string, unknown> | ((value: T) => boolean),
returnArray?: false,
): Promise<Map<string, T>>;
async findMany(
filter: Record<string, unknown> | ((value: T) => boolean),
returnArray?: true,
): Promise<T[]>;
async findMany(
filter: Record<string, unknown> | ((value: T) => boolean),
returnArray = false,
) {
const data = new Map<string, T>();
for await (
const file of Deno.readDir(
Deno.realPathSync(`${this.kwik.directoryPath}${this.tableName}`),
)
) {
if (!file.name || !file.isFile) continue;
try {
const name = file.name.substring(0, file.name.lastIndexOf("."));
const decodedData = await this.get(name);
if (decodedData) {
if (typeof filter === "function") {
if (filter(decodedData)) data.set(name, decodedData);
} else {
const invalid = Object.keys(filter).find((key) =>
(decodedData as unknown as Record<string, unknown>)[key] !==
filter[key]
);
if (!invalid) data.set(name, decodedData);
}
}
} catch (error) {
await this.kwik.error(
`[Kwik Error: findMany]: Unable to read file ${this.kwik.directoryPath}${this.tableName}/${file.name}`,
error,
);
}
}
return returnArray ? [...data.values()] : data;
}
/** Gets the first document from a table that match a filter */
async findOne(filter: Record<string, unknown> | ((value: T) => boolean)) {
for await (
const file of Deno.readDir(
Deno.realPathSync(`${this.kwik.directoryPath}${this.tableName}`),
)
) {
if (!file.name || !file.isFile) continue;
try {
const name = file.name.substring(0, file.name.lastIndexOf("."));
const decodedData = await this.get(name);
if (decodedData) {
if (typeof filter === "function") {
if (filter(decodedData)) return decodedData;
} else {
const invalid = Object.keys(filter).find((key) =>
(decodedData as unknown as Record<string, unknown>)[key] !==
filter[key]
);
if (!invalid) return decodedData;
}
}
} catch (error) {
await this.kwik.error(
`[Kwik Error: findOne]: Unable to read file ${this.kwik.directoryPath}${this.tableName}/${file.name}`,
error,
);
}
}
}
/** Set a document data. */
async set(id: string, data: Partial<T> = {}) {
return await this.saveFile(id, data);
}
/** Updates a documents' data. If this document does not exist, it will create the document. */
async update(id: string, data: Partial<T> = {}) {
const existing = await this.get(id) || {};
return this.set(id, existing ? { ...existing, ...data } : data);
}
/** Gets the first document from a table that match a filter */
async updateOne(
filter: Partial<T> | ((value: T) => boolean),
data: Partial<T>,
) {
for await (
const file of Deno.readDir(
Deno.realPathSync(`${this.kwik.directoryPath}${this.tableName}`),
)
) {
if (!file.name || !file.isFile) continue;
try {
const name = file.name.substring(0, file.name.lastIndexOf("."));
const decodedData = await this.get(name);
if (decodedData) {
if (typeof filter === "function") {
if (filter(decodedData)) return this.update(name, data);
} else {
const invalid = Object.keys(filter).find((key) =>
(decodedData as unknown as Record<string, unknown>)[key] !== // deno-lint-ignore no-explicit-any
(filter as any)[key]
);
if (!invalid) return this.update(name, data);
}
}
} catch (error) {
await this.kwik.error(
`[Kwik Error: updateOne]: Unable to read file ${this.kwik.directoryPath}${this.tableName}/${file.name}`,
error,
);
}
}
}
/** Deletes a document from the table. */
async delete(id: string): Promise<boolean> {
try {
await Deno.remove(
`${this.kwik.directoryPath}${this.tableName}/${id}.kwik`,
);
return true;
} catch (error) {
await this.kwik.error(
`[Kwik: delete]: Unable to delete file ${this.kwik.directoryPath}${this.tableName}/${id}.json`,
error,
);
return false;
}
}
/** Deletes one document in a table that match a filter */
async deleteOne(filter: Partial<T> | ((value: T) => boolean)) {
const files = Deno.readDirSync(
Deno.realPathSync(`${this.kwik.directoryPath}${this.tableName}`),
);
for (const file of files) {
if (!file.name || !file.isFile) continue;
try {
const name = file.name.substring(0, file.name.lastIndexOf("."));
const decodedData = await this.get(name);
if (decodedData) {
if (typeof filter === "function") {
return this.delete(name);
} else {
const invalid = Object.keys(filter).find((key) =>
(decodedData as unknown as Record<string, unknown>)[key] !== // deno-lint-ignore no-explicit-any
(filter as any)[key]
);
if (!invalid) return this.delete(name);
}
}
} catch (error) {
await this.kwik.error(
`[Kwik Error: deleteMany]: Unable to read file ${this.kwik.directoryPath}${this.tableName}/${file.name}`,
error,
);
}
}
}
/** Deletes all documents in a table that match a filter */
async deleteMany(filter: Partial<T> | ((value: T) => boolean)) {
const files = Deno.readDirSync(
Deno.realPathSync(`${this.kwik.directoryPath}${this.tableName}`),
);
for (const file of files) {
if (!file.name || !file.isFile) continue;
try {
const name = file.name.substring(0, file.name.lastIndexOf("."));
const decodedData = await this.get(name);
if (decodedData) {
if (typeof filter === "function") {
await this.delete(name);
} else {
const invalid = Object.keys(filter).find((key) =>
(decodedData as unknown as Record<string, unknown>)[key] !== // deno-lint-ignore no-explicit-any
(filter as any)[key]
);
if (!invalid) await this.delete(name);
}
}
} catch (error) {
await this.kwik.error(
`[Kwik Error: deleteMany]: Unable to read file ${this.kwik.directoryPath}${this.tableName}/${file.name}`,
error,
);
}
}
}
}