Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IndexedDB implementation without versionobject and backups #7

Merged
merged 5 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@
"typescript": "^5.4.4"
},
"dependencies": {
"inversify": "^6.0.2",
"@nlpjs/core": "^4.26.1",
"@nlpjs/lang-en": "^4.26.1",
"neverthrow": "^6.1.0",
"neverthrow": "^5.1.0",
"ts-brand": "^0.1.0"
}
}
18 changes: 18 additions & 0 deletions src/implementations/CrunchDB.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ContainerModule, interfaces } from 'inversify';
import { IndexedDB } from 'crunchDB/implementations/business/IndexedDB';
import {
IIndexedDB,
IIndexedDBType,
} from 'crunchDB/interfaces/business/IIndexedDB';
export const crunchDBModule = new ContainerModule(
(
bind: interfaces.Bind,
_unbind: interfaces.Unbind,
_isBound: interfaces.IsBound,
_rebind: interfaces.Rebind
) => {
bind<IIndexedDB>(IIndexedDBType)
.to(IndexedDB)
.inSingletonScope();
}
);
26 changes: 26 additions & 0 deletions src/implementations/CrunchDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { injectable } from 'inversify';
import { ICrunchDB } from 'crunchDB/interfaces/ICrunchDB';
import {
IIndexedDB,
IIndexedDBType,
} from 'crunchDB/interfaces/business/IIndexedDB';

@injectable()
export class CrunchDB implements ICrunchDB {
private dbService: IIndexedDB;

constructor(@inject(IIndexedDBType) dbService: IIndexedDB) {
this.dbService = dbService;
}

async initializeDatabase(): Promise<void> {
this.dbService
.init()
.map(() => {
console.log('Database initialized successfully.');
})
.mapErr(e => {
console.error(`Failed to initialize database: ${e.message}`);
});
}
}
134 changes: 134 additions & 0 deletions src/implementations/business/IndexedDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { injectable } from 'inversify';
import { ResultAsync } from 'neverthrow';
import { IDBConfig } from 'crunchDB/objects/business/IDBConfig';
import { VolatileObject } from 'crunchDB/objects/business/SimpleObject';
import { IIndexedDB } from 'crunchDB/interfaces/business/IIndexedDB';

@injectable()
export class IndexedDB implements IIndexedDB {
private db: IDBDatabase | null = null;

constructor(private config: IDBConfig) {}

init(): ResultAsync<void, Error> {
return ResultAsync.fromPromise(
new Promise<void>((resolve, reject) => {
const request = indexedDB.open(this.config.dbName, this.config.version);
request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
const db = request.result;
for (const storeConfig of this.config.stores) {
if (!db.objectStoreNames.contains(storeConfig.name)) {
const store = db.createObjectStore(storeConfig.name, {
keyPath: storeConfig.keyPath,
autoIncrement: storeConfig.autoIncrement ?? false,
});

storeConfig.indices?.forEach(index => {
store.createIndex(index.name, index.keyPath, index.options);
});
}
}
};
request.onsuccess = () => {
this.db = request.result;
resolve();
};
request.onerror = () => reject(new Error('Failed to open database'));
}),
e => new Error(`Database initialization failed: ${e}`)
);
}

addObject(
storeName: string,
VolatileObject: VolatileObject
): ResultAsync<void, Error> {
return this.transaction(storeName, 'readwrite', store =>
store.add(VolatileObject)
).map(() => undefined);
}

getObject(
storeName: string,
id: number
): ResultAsync<VolatileObject, Error> {
return this.transaction(storeName, 'readonly', store => store.get(id));
}

getAllObjects(
storeName: string
): ResultAsync<VolatileObject[], Error> {
return ResultAsync.fromPromise(
new Promise<VolatileObject[]>((resolve, reject) => {
if (!this.db) return reject(new Error('DB is not initialized'));
const transaction = this.db.transaction(storeName, 'readonly');
const store = transaction.objectStore(storeName);
const request = store.openCursor();
const VolatileObjects: VolatileObject[] = [];

request.onsuccess = () => {
const cursor = request.result;
if (cursor) {
VolatileObjects.push(cursor.value);
cursor.continue();
} else {
resolve(VolatileObjects);
}
};

transaction.onerror = () => reject(new Error('Transaction failed'));
request.onerror = () => reject(new Error('Request failed'));
}),
e => new Error(`Error fetching all VolatileObjects: ${e}`)
);
}

getAllItems(storeName: string): ResultAsync<VolatileObject[], Error> {
return ResultAsync.fromPromise(
new Promise<VolatileObject[]>((resolve, reject) => {
if (!this.db) {
reject(new Error('DB is not initialized'));
return;
}
const transaction = this.db.transaction(storeName, 'readonly');
const store = transaction.objectStore(storeName);
const request = store.openCursor();
const items: VolatileObject[] = [];

request.onsuccess = () => {
const cursor = request.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
} else {
resolve(items); // Resolve the array of items once cursor has iterated through all the entries
}
};

transaction.onerror = () => reject(new Error('Transaction failed'));
request.onerror = () => reject(new Error('Cursor operation failed'));
}),
e => new Error(`Error fetching all items with cursor: ${e}`)
);
}

private transaction<T>(
storeName: string,
mode: IDBTransactionMode,
action: (store: IDBObjectStore) => IDBRequest<T>
): ResultAsync<T, Error> {
return ResultAsync.fromPromise(
new Promise<T>((resolve, reject) => {
if (!this.db) return reject(new Error('DB is not initialized'));
const transaction = this.db.transaction(storeName, mode);
const store = transaction.objectStore(storeName);
const request = action(store);

transaction.oncomplete = () => resolve(request.result);
transaction.onerror = () => reject(new Error('Transaction failed'));
request.onerror = () => reject(new Error('Request operation failed'));
}),
e => new Error(`Transaction error: ${e}`)
);
}
}
1 change: 1 addition & 0 deletions src/interfaces/ICrunchDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export interface ICrunchDB {}
20 changes: 20 additions & 0 deletions src/interfaces/business/IIndexedDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// IIndexedDB.ts
import { ResultAsync } from 'neverthrow';
import { SimpleObject } from 'crunchDB/objects/business/SimpleObject';

export interface IIndexedDB {
init(): ResultAsync<void, Error>;

addObject(
storeName: string,
VolatileObject: SimpleObject
): ResultAsync<void, Error>;

getObject(storeName: string, id: number): ResultAsync<SimpleObject, Error>;

getAllObjects(storeName: string): ResultAsync<SimpleObject[], Error>;

getAllItems(storeName: string): ResultAsync<SimpleObject[], Error>;
}

export const IIndexedDBType = Symbol.for('IIndexedDB');
18 changes: 18 additions & 0 deletions src/objects/business/IDBConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export interface IDBConfig {
dbName: string;
version: number;
stores: StoreConfig[];
}

export interface StoreConfig {
name: string;
keyPath: string;
autoIncrement?: boolean;
indices?: IndexConfig[];
}

export interface IndexConfig {
name: string;
keyPath: string | string[];
options?: IDBIndexParameters;
}
6 changes: 6 additions & 0 deletions src/objects/business/SimpleObject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//@TODO add properties and rename the file to VolatileObject.ts
export interface SimpleObject {
id: number;
name: string;
value: string;
}
13 changes: 9 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3871,6 +3871,11 @@ interpret@^1.0.0:
resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz#665ab8bc4da27a774a40584e812e3e0fa45b1a1e"
integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==

inversify@^6.0.2:
version "6.0.2"
resolved "https://registry.yarnpkg.com/inversify/-/inversify-6.0.2.tgz#dc7fa0348213d789d35ffb719dea9685570989c7"
integrity sha512-i9m8j/7YIv4mDuYXUAcrpKPSaju/CIly9AHK5jvCBeoiM/2KEsuCQTTP+rzSWWpLYWRukdXFSl6ZTk2/uumbiA==

ip-regex@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/ip-regex/-/ip-regex-2.1.0.tgz#fa78bf5d2e6913c911ce9f819ee5146bb6d844e9"
Expand Down Expand Up @@ -5145,10 +5150,10 @@ natural-compare@^1.4.0:
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==

neverthrow@^6.1.0:
version "6.1.0"
resolved "https://registry.yarnpkg.com/neverthrow/-/neverthrow-6.1.0.tgz#51a6e9ce2e06600045b3c1b37aecc536d267bf95"
integrity sha512-xNbNjp/6M5vUV+mststgneJN9eJeJCDSYSBTaf3vxgvcKooP+8L0ATFpM8DGfmH7UWKJeoa24Qi33tBP9Ya3zA==
neverthrow@^5.1.0:
version "5.1.0"
resolved "https://registry.yarnpkg.com/neverthrow/-/neverthrow-5.1.0.tgz#709bcb477fa6bcf0c1f6a3f875d8a1a2eee0e46d"
integrity sha512-tgoYQZjAG+30dcUM35FL8FSQA52WQ6QPnk9laHUZBZ7CliB2vdR1aU7Svr10kyHJ3gwTzMTAajKT5xbdi0QS+Q==

nice-try@^1.0.4:
version "1.0.5"
Expand Down
Loading