Skip to content

Commit

Permalink
chore: code tidying
Browse files Browse the repository at this point in the history
  • Loading branch information
chrismclarke committed Oct 10, 2023
1 parent 2923270 commit 469961e
Show file tree
Hide file tree
Showing 13 changed files with 47 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ dependencies {
implementation project(':capacitor-browser')
implementation project(':capacitor-device')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-network')
implementation project(':capacitor-blob-writer')
implementation project(':capacitor-video-player')
implementation project(':capacitor-community-firebase-analytics')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@capacitor/core",
"@capacitor/device",
"@capacitor/filesystem",
"@capacitor/network",
"capacitor-blob-writer",
"capacitor-video-player",
"@capacitor-community/firebase-analytics",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
"pkg": "@capacitor/filesystem",
"classpath": "com.capacitorjs.plugins.filesystem.FilesystemPlugin"
},
{
"pkg": "@capacitor/network",
"classpath": "com.capacitorjs.plugins.network.NetworkPlugin"
},
{
"pkg": "capacitor-blob-writer",
"classpath": "com.equimaps.capacitorblobwriter.BlobWriter"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ project(':capacitor-device').projectDir = new File('../../../../node_modules/@ca
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../../../../node_modules/@capacitor/filesystem/android')

include ':capacitor-network'
project(':capacitor-network').projectDir = new File('../../../../node_modules/@capacitor/network/android')

include ':capacitor-blob-writer'
project(':capacitor-blob-writer').projectDir = new File('../../../../node_modules/capacitor-blob-writer/android')

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ISupabasePushEntry } from '@picsa/shared/services/core/db_v2/db-supabase-push.service';
import { ISyncPushEntry } from '@picsa/shared/services/core/db_v2/db-sync.service';
import { arrayToHashmapArray, hashmapToArray } from '@picsa/utils';
import { Subject, takeUntil } from 'rxjs';

Expand All @@ -9,7 +9,7 @@ import { IFormSubmission } from '../../schema/submissions';
import { MonitoringToolService } from '../../services/monitoring-tool.service';

type ISyncStatus = {
[status in ISupabasePushEntry['_supabase_push_status']]: {
[status in ISyncPushEntry['_sync_push_status']]: {
value: number;
matIcon: string;
id?: string;
Expand Down Expand Up @@ -54,7 +54,7 @@ export class FormItemComponent implements OnInit, OnDestroy {
const submissionsQuery = this.service.getFormSubmissionsQuery(this.form._id);
submissionsQuery.$.pipe(takeUntil(this.componentDestroyed$)).subscribe((docs) => {
const submissions = docs.map((d) => d.toMutableJSON());
const submissionsByStatus = arrayToHashmapArray<IFormSubmission>(submissions, '_supabase_push_status');
const submissionsByStatus = arrayToHashmapArray<IFormSubmission>(submissions, '_sync_push_status');
for (const status of Object.keys(this.syncStatusMap)) {
this.syncStatusMap[status].value = submissionsByStatus[status]?.length || 0;
}
Expand Down
4 changes: 2 additions & 2 deletions apps/picsa-tools/monitoring-tool/src/app/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ISupabasePushEntry } from '@picsa/shared/services/core/db_v2/db-supabase-push.service';
import { ISyncPushEntry } from '@picsa/shared/services/core/db_v2/db-sync.service';

export const STATUS_ICONS: {
[status in ISupabasePushEntry['_supabase_push_status']]: {
[status in ISyncPushEntry['_sync_push_status']]: {
matIcon: string;
};
} = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export class FormViewComponent implements OnInit, OnDestroy {
json: afterJson,
enketoEntry: this.formEntry,
_modified: new Date().toISOString(),
_supabase_push_status: this.formEntry?.draft ? 'draft' : 'ready',
_sync_push_status: this.formEntry?.draft ? 'draft' : 'ready',
};
return this.submissionDoc.incrementalPatch(patch);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export class SubmissionListComponent implements OnInit, OnDestroy {
}

public get dataSourceColumns() {
return [...this.displayedColumns, '_supabase_push_status'];
return [...this.displayedColumns, '_sync_push_status'];
}

private async loadForm(formId: string) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import { generateID } from '@picsa/shared/services/core/db/db.service';
import type { IPicsaCollectionCreator } from '@picsa/shared/services/core/db_v2';
import { ISupabasePushEntry } from '@picsa/shared/services/core/db_v2/db-supabase-push.service';
import { ISyncPushEntry } from '@picsa/shared/services/core/db_v2/db-sync.service';
import { RxJsonSchema } from 'rxdb';

import { IFormSubmission_V1, SCHEMA_V1 } from './schema_V1';

/**
* DB forms include basic metadata on
* */
export type IFormSubmission_V2 = IFormSubmission_V1 & ISupabasePushEntry;
export type IFormSubmission_V2 = IFormSubmission_V1 & ISyncPushEntry;

export const SCHEMA_V2: RxJsonSchema<IFormSubmission_V2> = {
...SCHEMA_V1,
properties: {
...SCHEMA_V1.properties,
_supabase_push_status: { type: 'string' },
_sync_push_status: { type: 'string' },
},
version: 2,
};

export const COLLECTION_V2: IPicsaCollectionCreator<IFormSubmission_V2> = {
schema: SCHEMA_V2,
isUserCollection: true,
pushToSupabase: true,
syncPush: true,
migrationStrategies: {
2: (data: IFormSubmission_V1) => {
const migrated: IFormSubmission_V2 = {
...data,
_supabase_push_status: 'ready',
_sync_push_status: 'ready',
};
return migrated;
},
Expand All @@ -39,7 +39,7 @@ export const ENTRY_TEMPLATE_V2 = (formId: string): IFormSubmission_V2 => ({
_id: generateID(),
_created: new Date().toISOString(),
_modified: new Date().toISOString(),
_supabase_push_status: 'draft',
_sync_push_status: 'draft',
formId,
json: {},
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable } from '@angular/core';
import { PicsaAsyncService } from '@picsa/shared/services/asyncService.service';
import { PicsaDatabase_V2_Service } from '@picsa/shared/services/core/db_v2';
import { PicsaDatabaseSupabasePushService } from '@picsa/shared/services/core/db_v2/db-supabase-push.service';
import { PicsaDatabaseSyncService } from '@picsa/shared/services/core/db_v2/db-sync.service';
import { RxCollection } from 'rxdb';

import { HARDCODED_FORMS } from '../../../data/forms';
Expand All @@ -10,10 +10,10 @@ import * as SubmissionSchema from '../schema/submissions';

@Injectable({ providedIn: 'root' })
export class MonitoringToolService extends PicsaAsyncService {
/** Track number of items pending push to supabase db (0 value implies fully synced) */
/** Track number of items pending push to server db (0 value implies fully synced) */
public pendingSyncCount = -1;

constructor(private dbService: PicsaDatabase_V2_Service, private syncService: PicsaDatabaseSupabasePushService) {
constructor(private dbService: PicsaDatabase_V2_Service, private syncService: PicsaDatabaseSyncService) {
super();
}

Expand Down Expand Up @@ -76,7 +76,7 @@ export class MonitoringToolService extends PicsaAsyncService {
}

private listPendingSync() {
const selector = { _supabase_push_status: 'ready' };
const selector = { _sync_push_status: 'ready' };
this.dbSubmissionsCollection.find({ selector }).$.subscribe((res) => {
this.pendingSyncCount = res.length;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,22 @@ import { RxCollection, RxDocument } from 'rxdb';

import { SupabaseService } from '../supabase.service';

export interface ISupabasePushEntry {
_supabase_push_status: 'draft' | 'ready' | 'complete' | 'failed';
export interface ISyncPushEntry {
_sync_push_status: 'draft' | 'ready' | 'complete' | 'failed';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}

/** Any collection marked as a supabasePushCollection will have metadata fields appended */
// type ISupabasePushCollection = RxCollection<RxJsonSchema<ISupabasePushEntry>>;

/**
* Simple service to push a replica of data to supabase server
*
* TODO - Row level security
* TODO - managing auth users in app (app_user_id with global user id)
*
* NOTE - is single direction push only, for full replication see:
* https://github.com/marceljuenemann/rxdb-supabase/tree/main
*/
@Injectable({ providedIn: 'root' })
export class PicsaDatabaseSupabasePushService {
export class PicsaDatabaseSyncService {
private registeredCollections: Record<string, RxCollection> = {};

constructor(private supabaseService: SupabaseService) {
Expand All @@ -50,8 +46,8 @@ export class PicsaDatabaseSupabasePushService {
* */
public async syncPendingDocs(collection: RxCollection) {
await this.supabaseService.ready();
const docs: RxDocument<ISupabasePushEntry>[] = await collection
.find({ selector: { _supabase_push_status: 'ready' } })
const docs: RxDocument<ISyncPushEntry>[] = await collection
.find({ selector: { _sync_push_status: 'ready' } })
.exec();
if (docs.length > 0) {
return this.pushDocsToSupabase(docs, collection);
Expand Down Expand Up @@ -87,27 +83,27 @@ export class PicsaDatabaseSupabasePushService {
private async subscribeToCollectionChanges(collection: RxCollection) {
collection.$.subscribe(async (change) => {
// TODO - update only if ready for submission, maybe debounce
const { _supabase_push_status } = change.documentData as ISupabasePushEntry;
if (_supabase_push_status === 'ready' || _supabase_push_status === 'complete') {
const { _sync_push_status } = change.documentData as ISyncPushEntry;
if (_sync_push_status === 'ready' || _sync_push_status === 'complete') {
await this.pushDocsToSupabase([{ _data: change.documentData } as any], collection);
}
});
}

private async pushDocsToSupabase(docs: RxDocument<ISupabasePushEntry>[], collection: RxCollection) {
private async pushDocsToSupabase(docs: RxDocument<ISyncPushEntry>[], collection: RxCollection) {
const records = docs.map((d) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { _meta, _rev, _supabase_push_status, ...keptFields } = d._data as ISupabasePushEntry;
const { _meta, _rev, _sync_push_status, ...keptFields } = d._data as ISyncPushEntry;
return keptFields;
});
const table = this.supabaseService.db.table(collection.name);
const res = await table.upsert(records);
if (res.status === 201) {
// update local collection status where applicatble
const successUpdate = docs
.filter((d) => d._data._supabase_push_status !== 'complete')
.filter((d) => d._data._sync_push_status !== 'complete')
.map((d) => {
d._data._supabase_push_status = 'complete';
d._data._sync_push_status = 'complete';
return d._data;
});
await collection.bulkUpsert(successUpdate);
Expand Down
16 changes: 8 additions & 8 deletions libs/shared/src/services/core/db_v2/db.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie';

import { PicsaAsyncService } from '../../asyncService.service';
import { PicsaUserService } from '../user.service';
import { ISupabasePushEntry, PicsaDatabaseSupabasePushService } from './db-supabase-push.service';
import { PicsaDatabaseSyncService } from './db-sync.service';
import { IPicsaCollectionCreator } from './models';

addRxPlugin(RxDBAttachmentsPlugin);
Expand All @@ -31,7 +31,7 @@ export class PicsaDatabase_V2_Service extends PicsaAsyncService {
[key: string]: RxCollection;
}>;

constructor(private userService: PicsaUserService, private pushService: PicsaDatabaseSupabasePushService) {
constructor(private userService: PicsaUserService, private pushService: PicsaDatabaseSyncService) {
super();
}

Expand Down Expand Up @@ -68,8 +68,8 @@ export class PicsaDatabase_V2_Service extends PicsaAsyncService {
hookFactory(createdCollection);
}

// register supabase push
if (picsaCollection.pushToSupabase) {
// register sync push
if (picsaCollection.syncPush) {
this.pushService.registerCollection(createdCollection);
}
}
Expand Down Expand Up @@ -97,7 +97,7 @@ export class PicsaDatabase_V2_Service extends PicsaAsyncService {
* Handle custom PICSA DB modifiers
*/
private handleCollectionModifiers(picsaCollection: IPicsaCollectionCreator<any>) {
const { isUserCollection, pushToSupabase, ...collection } = picsaCollection;
const { isUserCollection, syncPush, ...collection } = picsaCollection;
const hookFactories: ((c: RxCollection) => void)[] = [];
// store app user ids in any collections marked with `isUserCollection`
// user information is stored in localStorage instead of db to avoid circular dependency issues
Expand All @@ -109,9 +109,9 @@ export class PicsaDatabase_V2_Service extends PicsaAsyncService {
c.addHook('pre', 'insert', fn);
});
}
// If collection pushed to supabase store _supabase_push_status
if (pushToSupabase) {
collection.schema.properties['_supabase_push_status'] = { type: 'string' };
// If collection pushed to server db store _sync_push_status
if (syncPush) {
collection.schema.properties['_sync_push_status'] = { type: 'string' };
}
return { collection, hookFactories };
}
Expand Down
4 changes: 2 additions & 2 deletions libs/shared/src/services/core/db_v2/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { RxCollectionCreator } from 'rxdb';
export interface IPicsaCollectionCreator<T> extends RxCollectionCreator<T> {
/** User collections will append app user id to all entries */
isUserCollection: boolean;
/** Push a copy of all data to supabase */
pushToSupabase?: boolean;
/** Push a copy of all data to server db */
syncPush?: boolean;
}

0 comments on commit 469961e

Please sign in to comment.