From b8112947cdd784ea6bbad6d662e1e8f9e37c8e8e Mon Sep 17 00:00:00 2001 From: Jason Kulatunga Date: Tue, 11 Oct 2022 22:43:42 -0700 Subject: [PATCH] WIP, writing directly to the remote DB. --- .../src/app/services/fasten-db.service.ts | 60 ++++++++++--------- .../src/lib/database/pouchdb_repository.ts | 38 ++++++------ 2 files changed, 52 insertions(+), 46 deletions(-) diff --git a/frontend/src/app/services/fasten-db.service.ts b/frontend/src/app/services/fasten-db.service.ts index 79784d0b..4ba3a659 100644 --- a/frontend/src/app/services/fasten-db.service.ts +++ b/frontend/src/app/services/fasten-db.service.ts @@ -46,7 +46,7 @@ export class FastenDbService extends PouchdbRepository { let remotePouchDb = new PouchDB(this.getRemoteUserDb(username), {skip_setup: true}); return await remotePouchDb.logIn(username, pass) .then((loginResp)=>{ - return this.postLoginHook(loginResp.name, true) + return this.postLoginHook(loginResp.name, remotePouchDb) }) .catch((err) => { console.error("an error occurred during login/setup", err) @@ -68,13 +68,17 @@ export class FastenDbService extends PouchdbRepository { public async Logout(): Promise { - let remotePouchDb = new PouchDB(this.getRemoteUserDb(localStorage.getItem("current_user")), {skip_setup: true}); - await remotePouchDb.logOut() + // let remotePouchDb = new PouchDB(this.getRemoteUserDb(localStorage.getItem("current_user")), {skip_setup: true}); + if(this.pouchDb){ + await this.pouchDb.logOut() + } await this.Close() localStorage.removeItem("current_user") } + + //TODO: now that we've moved to remote-first database, we can refactor and simplify this function significantly. public async IsAuthenticated(): Promise { - if(!this.localPouchDb){ + if(!this.pouchDb){ console.warn("IsAuthenticated? ====> logout, no local database present") //if no local database available, we're always "unauthenticated". return false @@ -85,8 +89,8 @@ export class FastenDbService extends PouchdbRepository { } try{ //if we have a local database, lets see if we have an active session to the remote database. - const remotePouchDb = new PouchDB(this.getRemoteUserDb(localStorage.getItem("current_user")), {skip_setup: true}); - const session = await remotePouchDb.getSession() + // const remotePouchDb = new PouchDB(this.getRemoteUserDb(localStorage.getItem("current_user")), {skip_setup: true}); + const session = await this.pouchDb.getSession() const authUser = session?.userCtx?.name const isAuth = !!authUser console.warn("IsAuthenticated? getSession() ====> ", isAuth) @@ -165,16 +169,18 @@ export class FastenDbService extends PouchdbRepository { * @param userIdentifier * @constructor */ - private async postLoginHook(userIdentifier: string, sync: boolean = false): Promise { + private async postLoginHook(userIdentifier: string, pouchDb: PouchDB.Database): Promise { localStorage.setItem("current_user", userIdentifier) await this.Close(); - this.localPouchDb = new PouchDB(userIdentifier); + this.pouchDb = pouchDb; //create any necessary indexes // this index allows us to group by source_resource_type console.log("DB createIndex started...") - const createIndexMsg = await this.localPouchDb.createIndex({ + //todo, we may need to wait a couple of moments before starting this index, as the database may not exist yet (even after user creation) + await (new Promise((resolve) => setTimeout(resolve, 500))) //sleep for 0.5s. + const createIndexMsg = await this.pouchDb.createIndex({ index: {fields: [ 'doc_type', 'source_resource_type', @@ -182,25 +188,25 @@ export class FastenDbService extends PouchdbRepository { }); console.log("DB createIndex complete", createIndexMsg) - if(sync){ - console.log("DB sync init...", userIdentifier, this.getRemoteUserDb(userIdentifier)) + // if(sync){ + // console.log("DB sync init...", userIdentifier, this.getRemoteUserDb(userIdentifier)) + // + // // this.enableSync(userIdentifier) + // // .on('paused', function (info) { + // // // replication was paused, usually because of a lost connection + // // console.warn("replication was paused, usually because of a lost connection", info) + // // }).on('active', function (info) { + // // // replication was resumed + // // console.warn("replication was resumed", info) + // // }).on('error', function (err) { + // // // totally unhandled error (shouldn't happen) + // // console.error("replication unhandled error (shouldn't happen)", err) + // // }); + // console.log("DB sync enabled") + // + // } - this.enableSync(userIdentifier) - // .on('paused', function (info) { - // // replication was paused, usually because of a lost connection - // console.warn("replication was paused, usually because of a lost connection", info) - // }).on('active', function (info) { - // // replication was resumed - // console.warn("replication was resumed", info) - // }).on('error', function (err) { - // // totally unhandled error (shouldn't happen) - // console.error("replication unhandled error (shouldn't happen)", err) - // }); - console.log("DB sync enabled") - - } - - console.warn( "Configured PouchDB database for,", this.localPouchDb.name ); + console.warn( "Configured PouchDB database for,", this.pouchDb.name ); return } diff --git a/frontend/src/lib/database/pouchdb_repository.ts b/frontend/src/lib/database/pouchdb_repository.ts index 84cb735b..7d0ecc0a 100644 --- a/frontend/src/lib/database/pouchdb_repository.ts +++ b/frontend/src/lib/database/pouchdb_repository.ts @@ -48,10 +48,10 @@ export function NewRepositiory(userIdentifier?: string, encryptionKey?: string): export class PouchdbRepository implements IDatabaseRepository { - replicationHandler: any + // replicationHandler: any remotePouchEndpoint: string // "http://localhost:5984" encryptionKey: string - localPouchDb: PouchDB.Database + pouchDb: PouchDB.Database /** * This class can be initialized in 2 states @@ -65,11 +65,11 @@ export class PouchdbRepository implements IDatabaseRepository { //setup PouchDB Plugins //https://pouchdb.com/guides/mango-queries.html - this.localPouchDb = null + this.pouchDb = null if(userIdentifier){ - this.localPouchDb = new PouchDB(userIdentifier); + this.pouchDb = new PouchDB(this.getRemoteUserDb(userIdentifier)); this.encryptionKey = encryptionKey - this.enableSync(userIdentifier) + // this.enableSync(userIdentifier) } } @@ -79,16 +79,16 @@ export class PouchdbRepository implements IDatabaseRepository { // CAUTION: Subsequent calls to .GetDB() will fail until a new instance is configured // with a call to .ConfigureForUser(). public async Close(): Promise { - if (!this.localPouchDb) { + if (!this.pouchDb) { return; } // Stop remote replication for existing database - if(this.replicationHandler){ - this.replicationHandler.cancel() - } + // if(this.replicationHandler){ + // this.replicationHandler.cancel() + // } - this.localPouchDb.close(); - this.localPouchDb = null; + this.pouchDb.close(); + this.pouchDb = null; return } @@ -209,20 +209,20 @@ export class PouchdbRepository implements IDatabaseRepository { // Get the active PouchDB instance. Throws an error if no PouchDB instance is // available (ie, user has not yet been configured with call to .configureForUser()). public async GetDB(): Promise { - if(!this.localPouchDb) { + if(!this.pouchDb) { throw(new Error( "Database is not available - please configure an instance." )); } // if(this.encryptionKey){ - // return this.localPouchDb.crypto(this.encryptionKey, {ignore:[ + // return this.pouchDb.crypto(this.encryptionKey, {ignore:[ // 'doc_type', // 'source_id', // 'source_resource_type', // 'source_resource_id', // ]}).then(() => { - // return this.localPouchDb + // return this.pouchDb // }) // } else { - return this.localPouchDb; + return this.pouchDb; // } } @@ -377,10 +377,10 @@ export class PouchdbRepository implements IDatabaseRepository { protected getRemoteUserDb(username: string){ return `${this.remotePouchEndpoint}/userdb-${this.toHex(username)}` } - protected enableSync(userIdentifier: string){ - this.replicationHandler = this.localPouchDb.sync(this.getRemoteUserDb(userIdentifier), {live: true, retry: true}) - return - } + // protected enableSync(userIdentifier: string){ + // this.replicationHandler = this.localPouchDb.sync(this.getRemoteUserDb(userIdentifier), {live: true, retry: true}) + // return + // } private toHex(s: string) {