Skip to content

Commit

Permalink
fix: sync checks (#223)
Browse files Browse the repository at this point in the history
  • Loading branch information
akdasa authored May 24, 2023
1 parent 9543dfe commit a8ca0e3
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 47 deletions.
10 changes: 9 additions & 1 deletion src/app/settings/pages/AccountPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,16 @@ import {
IonHeader, IonPage, IonTitle, IonToolbar, IonLoading, IonIcon, useIonRouter, alertController
} from '@ionic/vue'
import { mail, logoApple, logoGoogle } from 'ionicons/icons'
import { computed } from 'vue'
import { computed, inject } from 'vue'
import { go, useAuthentication, useEmitter, useSync } from '@/app/shared'
import { useSettingsStore } from '@/app/settings'
import { CouchDB } from '@/services/persistence'
/* -------------------------------------------------------------------------- */
/* Dependencies */
/* -------------------------------------------------------------------------- */
const userDataDb = inject('userData') as CouchDB
const emitter = useEmitter()
const settings = useSettingsStore()
const auth = useAuthentication()
Expand Down Expand Up @@ -137,5 +139,11 @@ async function onEmailSignIn() {
async function onLogOut() {
settings.auth.sessionId = ''
settings.auth.token = ''
settings.auth.collectionId = ''
settings.auth.strategy = ''
settings.auth.expiresAt = undefined
settings.auth.refreshedAt = undefined
await userDataDb.destroy()
emitter.emit('syncCompleted')
}
</script>
2 changes: 1 addition & 1 deletion src/app/utils/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {


export function createRepositories(remote: string, token: string) {
const couchDB = new CouchDB(remote, undefined, token)
const couchDB = new CouchDB(remote, { token: token })

return new Repositories(
new InMemoryRepository<Verse>(),
Expand Down
9 changes: 7 additions & 2 deletions src/app/welcome/pages/WelcomePage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@
{{ $t("welcome.login.withEmail") }}
</IonButton>
<IonButton
router-link="/home/library"
router-direction="root"
expand="block"
fill="outline"
@click="onSigInAsGuest"
>
<ion-icon
slot="start"
Expand Down Expand Up @@ -116,14 +116,14 @@ async function onOpened() {
await syncLibraryTask.sync()
await loadLibrary.sync()
settingsStore.library.lastSyncDate = new Date().getTime()
settingsStore.welcome.done = true
}
async function onSignIn(strategy: string) {
try {
await auth.authenticate(strategy)
await syncTask.run()
emitter.emit('syncCompleted')
settingsStore.welcome.done = true
router.replace(go('library'))
} catch (e) {
const alert = await alertController.create({
Expand All @@ -139,6 +139,11 @@ async function onSignIn(strategy: string) {
async function onEmailSignIn() {
router.push(go('welcome-email'))
}
function onSigInAsGuest() {
settingsStore.welcome.done = true
router.replace(go('library'))
}
</script>


Expand Down
12 changes: 8 additions & 4 deletions src/init/infrastructure/initDatabases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ import { InitResult } from '../initialization'
* Initialize databases
*/
export async function initDatabases(): Promise<InitResult> {
const adapter = Capacitor.getPlatform() == 'ios' ? 'cordova-sqlite' : undefined
const config = {
adapter: Capacitor.getPlatform() == 'ios' ? 'cordova-sqlite' : undefined,
location: 'default'
}

return {
verses: new CouchDB('verses', adapter),
userData: new CouchDB('userData', adapter),
userDataTutorial: new CouchDB('tutorial:userData', adapter)
verses: new CouchDB('verses', config),
userData: new CouchDB('userData', config),
userDataTutorial: new CouchDB('tutorial:userData', config)
}
}
2 changes: 1 addition & 1 deletion src/services/auth/strategies/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { AuthenticationStrategy, AuthenticationResult } from './strategy'
export class EmailAuthenticationStrategy implements AuthenticationStrategy {
//@ts-ignore
async authenticate(data: any): Promise<AuthenticationResult> {
console.log(`lgoinig in with email "${data.email}", "${data.code}"`, data.email && !data.code)
console.log(`Signing in with email "${data.email}", "${data.code}"`, data.email && !data.code)
if (data.email && !data.code) {
// TODO:
//@ts-ignore
Expand Down
69 changes: 32 additions & 37 deletions src/services/persistence/PouchRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,21 @@ PouchDB.plugin(PouchdbFind)
PouchDB.plugin(PouchDBAdapterSqlLite)


export interface CouchDBConfig {
adapter?: string,
token?: string
location?: string
}

export class CouchDB {
private _db: PouchDB.Database
private _name: string
private _config: CouchDBConfig

constructor(dbName: string, adapter?: string, token?: string) {
if (adapter) {
this._db = new PouchDB(dbName, {
adapter: 'cordova-sqlite',
// revs_limit: 1,
// auto_compaction: true,
// @ts-ignore
location: 'default',
// iosDatabaseLocation: 'default',
// @ts-ignore
fetch: function (url, opts) {
opts.headers.set('Authorization', 'Bearer ' + token)
return PouchDB.fetch(url, opts)
}
})
} else {
this._db = new PouchDB(dbName, {
fetch: function (url, opts) {
// @ts-ignore
opts.headers.set('Authorization', 'Bearer ' + token)
return PouchDB.fetch(url, opts)
}
// revs_limit: 1,
// auto_compaction: true,
})
}
constructor(name: string, config: CouchDBConfig) {
this._name = name
this._config = config
this._db = this.creaateDatabase()
}

async sync(to: string) {
Expand All @@ -52,14 +38,23 @@ export class CouchDB {
return await this._db.replicate.from(from)
}

async deleteAll() {
const docs = await this._db.allDocs()
docs.rows.forEach(async y => {
await this._db.remove(y.id, y.value.rev)
})
async destroy() {
await this._db.destroy()
this._db = this.creaateDatabase()
}

get db(): PouchDB.Database { return this ._db }
get db(): PouchDB.Database { return this._db }

private creaateDatabase() {
return new PouchDB(this._name, {
...this._config,
fetch: (url, opts) => {
// @ts-ignore
opts.headers.set('Authorization', 'Bearer ' + this._config.token)
return PouchDB.fetch(url, opts)
}
})
}
}

export class PouchRepository<
Expand Down Expand Up @@ -146,7 +141,7 @@ export class PouchRepository<
try {
const doc = await this._db.db.get(id.value, { latest: true })
await this._db.db.remove(doc)
} catch(e) { console.log('CANT DELETE', e, this._collectionName) }
} catch (e) { console.log('CANT DELETE', e, this._collectionName) }
}
}

Expand Down Expand Up @@ -184,17 +179,17 @@ class QueryConverter {

// return query
return {
[query.field]: { [this.operatorsMap[query.operator]] : value }
[query.field]: { [this.operatorsMap[query.operator]]: value }
}
} else if (query instanceof Expression) {
if (query.operator === LogicalOperators.Or) {
return { '$or': [ ...query.query.map(x => this._visit(x)) ] }
return { '$or': [...query.query.map(x => this._visit(x))] }
}
if (query.operator === LogicalOperators.Not) {
return { '$not': deepMerge({}, ...query.query.map(x => this._visit(x)) ) }
return { '$not': deepMerge({}, ...query.query.map(x => this._visit(x))) }
}
if (query.operator === LogicalOperators.And) {
return { '$and': [ ...query.query.map(x => this._visit(x)) ] }
return { '$and': [...query.query.map(x => this._visit(x))] }
}

return deepMerge(
Expand Down
2 changes: 1 addition & 1 deletion src/services/persistence/ReviewCardSerializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class ReviewCardSerializer implements ObjectMapper<ReviewCard, any> {
'interval': from.interval,
'ease': from.ease,
'lapses': from.lapses,
'difficultyChangedAt': from.difficultyChangedAt,
'difficultyChangedAt': date(from.difficultyChangedAt),
}
}
}
Expand Down

0 comments on commit a8ca0e3

Please sign in to comment.