-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
188 lines (159 loc) · 5.57 KB
/
index.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
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
import 'reflect-metadata';
function KeyPath(): PropertyDecorator {
return (target: Object, propertyKey: string | symbol) => {
const constructor = target.constructor as Function;
Reflect.defineMetadata("keypath", [propertyKey as string], constructor);
};
}
function DataClass(): ClassDecorator {
return (target: Function) => {
if (!Reflect.getMetadata("keypath", target)) {
throw new Error(`No keypath field defined for the class ${target.name}.`);
}
const keyPathFields = Reflect.getMetadata("keypath", target) || [];
if (keyPathFields.length > 1) {
throw new Error(`Only one keypath field can be defined for the class ${target.name}.`);
}
Reflect.defineMetadata("dataclass", true, target);
};
}
class Database {
private dbName: string;
private classes: Function[];
private db: IDBDatabase | null = null;
private constructor(dbName: string, classes: Function[]) {
this.dbName = dbName;
if (!classes.every(cls => Reflect.getMetadata("dataclass", cls))) {
throw new Error("All classes should be decorated with @DataClass.");
}
this.classes = classes;
}
public static async build(dbName: string, classes: Function[]): Promise<Database> {
const instance = new Database(dbName, classes);
await instance.initDB();
return instance;
}
private async initDB(): Promise<void> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, 1);
request.onupgradeneeded = () => {
const db = request.result;
this.classes.forEach((cls) => {
const keyPathFields = Reflect.getMetadata("keypath", cls) || [];
const storeName = cls.name.toLowerCase() + "s";
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: keyPathFields[0] });
}
});
};
request.onsuccess = () => {
this.db = request.result;
console.log(`Database initialized with object stores for: ${this.classes.map(cls => cls.name).join(", ")}`);
resolve();
};
request.onerror = () => {
console.error("Error initializing database:", request.error);
reject(request.error);
};
});
}
private getObjectStore(className: string, mode: IDBTransactionMode): IDBObjectStore {
if (!this.db) {
throw new Error("Database not initialized.");
}
const storeName = className.toLowerCase() + "s";
const transaction = this.db.transaction(storeName, mode);
return transaction.objectStore(storeName);
}
async create<T>(cls: { new(...args: any[]): T }, item: T): Promise<void> {
return new Promise((resolve, reject) => {
try {
const store = this.getObjectStore(cls.name, "readwrite");
const request = store.add(item);
request.onsuccess = () => {
console.log(`Item added to ${cls.name}:`, item);
resolve();
};
request.onerror = () => {
console.error(`Error adding item to ${cls.name}:`, request.error);
reject(request.error);
};
} catch (error) {
reject(error);
}
});
}
async read<T>(cls: { new(...args: any[]): T }, key: string): Promise<T | undefined> {
return new Promise((resolve, reject) => {
try {
const store = this.getObjectStore(cls.name, "readonly");
const request = store.get(key);
request.onsuccess = () => {
console.log(`Item read from ${cls.name}:`, request.result);
resolve(request.result as T | undefined);
};
request.onerror = () => {
console.error(`Error reading item from ${cls.name}:`, request.error);
reject(request.error);
};
} catch (error) {
reject(error);
}
});
}
async update<T>(cls: { new(...args: any[]): T }, item: T): Promise<void> {
return new Promise((resolve, reject) => {
try {
const store = this.getObjectStore(cls.name, "readwrite");
const request = store.put(item);
request.onsuccess = () => {
console.log(`Item updated in ${cls.name}:`, item);
resolve();
};
request.onerror = () => {
console.error(`Error updating item in ${cls.name}:`, request.error);
reject(request.error);
};
} catch (error) {
reject(error);
}
});
}
async delete<T>(cls: { new(...args: any[]): T }, key: string): Promise<void> {
return new Promise((resolve, reject) => {
try {
const store = this.getObjectStore(cls.name, "readwrite");
const request = store.delete(key);
request.onsuccess = () => {
console.log(`Item deleted from ${cls.name}:`, key);
resolve();
};
request.onerror = () => {
console.error(`Error deleting item from ${cls.name}:`, request.error);
reject(request.error);
};
} catch (error) {
reject(error);
}
});
}
async list<T>(cls: { new(...args: any[]): T }): Promise<T[]> {
return new Promise((resolve, reject) => {
try {
const store = this.getObjectStore(cls.name, "readonly");
const request = store.getAll();
request.onsuccess = () => {
console.log(`All items from ${cls.name}:`, request.result);
resolve(request.result as T[]);
};
request.onerror = () => {
console.error(`Error listing items from ${cls.name}:`, request.error);
reject(request.error);
};
} catch (error) {
reject(error);
}
});
}
}
export { Database, KeyPath, DataClass };