deno.land / x / simpledb@0.3.0 / simpledb.ts

نووسراو ببینە
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
import { DatabaseConfig } from "./config.ts";import { partialContains } from "./functions.ts";
export class SimpleDB { private _data: object[] = []; private config: DatabaseConfig = { filePath: "./db.json" }
constructor(config?: DatabaseConfig) { if (typeof config !== "undefined") this.config = { ...this.config, ...config };
this.connect(); }
/* ===== PRIVATE ===== */ private async connect() { /* * Check if there is a database. Otherwise, create one. */ try { await Deno.lstat(this.config.filePath); } catch (err) { if (err instanceof Deno.errors.NotFound) { await Deno.writeTextFile(this.config.filePath, "[]"); console.log(`File created: ${this.config.filePath}`); } else throw err; }
/* * Read database file */ this._data = await JSON.parse(await Deno.readTextFileSync(this.config.filePath)); }
private async findIndexBy(ob: object) { return this._data.findIndex((x) => partialContains(x, ob)); }
private async findDataBy(ob: object) { return this._data.find((object) => partialContains(object, ob)); }
/* ===== PUBLIC ===== */ async save() { try { await Deno.writeTextFile(this.config.filePath, JSON.stringify(this._data, null, 2)); } catch (e) { throw e; } }
async insert(data: object):Promise<any> { do { var id = [ ...Array(24) ].map(() => (~~(Math.random() * 36)).toString(36)).join(''); } while (await this.findIndexBy({ _id: id }) !== -1);
data = Object.assign({ _id: id }, data); this._data.push(data); return data; }
async findOne(ob: object):Promise<any> { return await this.findDataBy(ob); }
async findOneAndUpdate(ob: object, replace: object):Promise<any> { let id = await this.findIndexBy(ob);
if (id === -1) return undefined;
this._data[id] = { ...this._data[id], ...replace }; return this._data[id]; }
async delete(ob: object):Promise<Boolean> { let result = await this.findIndexBy(ob); if (result === -1) return false; this._data.splice(result, 1); return true; }
async exists(ob: object):Promise<Boolean> { return this._data.some((object) => partialContains(object, ob)); }}
simpledb

Version Info

Tagged at
3 years ago

External Dependencies

No external dependencies 🎉