Skip to content

Commit

Permalink
backup and restore improved
Browse files Browse the repository at this point in the history
  • Loading branch information
ragsav committed Oct 6, 2022
1 parent 3627d96 commit 7bfa54c
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 50 deletions.
5 changes: 5 additions & 0 deletions constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ export const CONSTANTS = Object.freeze({
DAILY_REMINDER_ID: 1023,
NOTIFICATION_CLEAR_DELAY_BUFFER: 15 * 60 * 1000,

TABLE_NAMES: {
LABELS: 'labels',
NOTES: 'notes',
TASKS: 'tasks',
},
ROUTES: {
HOME: 'HOME',
INTRO: 'INTRO',
Expand Down
3 changes: 2 additions & 1 deletion js/components/TaskItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from 'react-native-paper';
import {connect} from 'react-redux';
import {CONSTANTS} from '../../constants';
import {database} from '../db/db';
import Task from '../db/models/Task';
import {
editTaskIsArchived,
Expand Down Expand Up @@ -265,7 +266,7 @@ const TaskItem = ({task, onLongPress, noteColor, isActive, dispatch, note}) => {
{task.description}
</Paragraph>
)}
{_renderNoteDetails(task.isArchived || task.isMarkedDeleted)}
{note && _renderNoteDetails(task.isArchived || task.isMarkedDeleted)}
{_renderArchiveTime()}
{_renderDeletionTime()}
{_renderDoneTime(!task.isArchived && !task.isMarkedDeleted)}
Expand Down
20 changes: 11 additions & 9 deletions js/db/models/Label.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
date,
readonly,
} from '@nozbe/watermelondb/decorators';
import {sanitizedRaw} from '@nozbe/watermelondb/RawRecord';
import {CONSTANTS} from '../../../constants';
import {database} from '../db';

export default class Label extends Model {
Expand All @@ -29,14 +31,14 @@ export default class Label extends Model {
@children('notes') notes;

static _backupToPrepareCreate = raw => {
return database.collections.get('notes').prepareCreate(label => {
label.id = raw.id;
label.title = raw.title;
label.iconString = raw.icon_string;
label.isArchived = raw.is_archived;
label.archiveTimestamp = raw.archive_timestamp;
label.isMarkedDeleted = raw.is_marked_deleted;
label.markedDeletedTimestamp = raw.marked_deleted_timestamp;
});
const collection = database.collections.get(CONSTANTS.TABLE_NAMES.LABELS);
return database.collections
.get(CONSTANTS.TABLE_NAMES.LABELS)
.prepareCreate(label => {
label._raw = sanitizedRaw({...raw}, collection.schema);
});
};
static _jsonDataForBackup = raw => {
return {...raw, _changed: null, _status: null};
};
}
22 changes: 11 additions & 11 deletions js/db/models/Note.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
readonly,
lazy,
} from '@nozbe/watermelondb/decorators';
import {sanitizedRaw} from '@nozbe/watermelondb/RawRecord';
import {CONSTANTS} from '../../../constants';
import {database} from '../db';
export default class Note extends Model {
static table = 'notes';
Expand All @@ -32,16 +34,14 @@ export default class Note extends Model {
@children('tasks') tasks;

static _backupToPrepareCreate = raw => {
return database.collections.get('notes').prepareCreate(note => {
note.id = raw.id;
note.title = raw.title;
note.description = raw.description;
note.colorString = raw.color_string;
note.labelID = raw.label_id;
note.isArchived = raw.is_archived;
note.archiveTimestamp = raw.archive_timestamp;
note.isMarkedDeleted = raw.is_marked_deleted;
note.markedDeletedTimestamp = raw.marked_deleted_timestamp;
});
const collection = database.collections.get(CONSTANTS.TABLE_NAMES.NOTES);
return database.collections
.get(CONSTANTS.TABLE_NAMES.NOTES)
.prepareCreate(note => {
note._raw = sanitizedRaw({...raw}, collection.schema);
});
};
static _jsonDataForBackup = raw => {
return {...raw, _changed: null, _status: null};
};
}
26 changes: 7 additions & 19 deletions js/db/models/Task.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
reader,
lazy,
} from '@nozbe/watermelondb/decorators';
import {sanitizedRaw} from '@nozbe/watermelondb/RawRecord';
import {CONSTANTS} from '../../../constants';
import {database} from '../db';
export default class Task extends Model {
static table = 'tasks';
Expand Down Expand Up @@ -44,26 +46,12 @@ export default class Task extends Model {
@relation('notes', 'note_id') note;

static _backupToPrepareCreate = raw => {
const collection = database.collections.get(CONSTANTS.TABLE_NAMES.TASKS);
return database.collections.get('tasks').prepareCreate(task => {
task.id = raw.id;
task.title = raw.title;
task.description = raw.description;
task.imageURIs = raw.image_uris;
task.noteID = raw.note_id;
task.isBookmarked = raw.is_bookmarked;
task.isDone = raw.is_done;
task.doneTimestamp = raw.done_timestamp;
task.priority = raw.priority;
task.startTimestamp = raw.start_timestamp;
task.endTimestamp = raw.end_timestamp;
task.reminderTimestamp = raw.reminder_timestamp;
task.reminderID = raw.reminder_id;
task.isRepeating = raw.is_repeating;
task.isArchived = raw.is_archived;
task.archiveTimestamp = raw.archive_timestamp;
task.isMarkedDeleted = raw.is_marked_deleted;
task.markedDeletedTimestamp = raw.marked_deleted_timestamp;
task.repeatCron = raw.repeat_cron;
task._raw = sanitizedRaw({...raw}, collection.schema);
});
};
static _jsonDataForBackup = raw => {
return {...raw, _changed: null, _status: null};
};
}
55 changes: 45 additions & 10 deletions js/db/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,19 @@ import RNFS from 'react-native-fs';
import Label from './models/Label';
import Note from './models/Note';
import Task from './models/Task';
import {CONSTANTS} from '../../constants';
export class WTDBSync {
/**
*
* @param {object} raw
* @param {Collection} collection
* @returns
*/
static _backupToPrepareCreate = (raw, collection) => {
return database.collections.get(collection.table).prepareCreate(label => {
label._raw = sanitizedRaw({...raw}, collection.schema);
});
};
static _prepareCreateFromDirtyRaw(collection, dirtyRaw) {
const sanitized = sanitizedRaw(dirtyRaw, collection.schema);
const record = new Model(collection, sanitized);
Expand Down Expand Up @@ -54,16 +66,21 @@ export class WTDBSync {
);
const promiseRecords = [];
const recordsData = {};

tables.forEach(table => {
promiseRecords.push(database.collections.get(table).query().fetch());
});

const resolvedRecords = await Promise.all(promiseRecords);
Logger.pageLogger('WTDBSync:fetchAllLocalRecords:resolvedRecords', {
resolvedRecords,
});
resolvedRecords.forEach((records, index) => {
recordsData[tables[index]] = records.map(record => {
return {...record._raw};
return {...record._raw, _changed: null, _status: null};
});
});

Logger.pageLogger('WTDBSync:fetchAllLocalRecords:recordsData', {
recordsData,
});
Expand All @@ -80,6 +97,7 @@ export class WTDBSync {

static loadDatabase = async ({setIsLoading, recordsData}) => {
try {
if (typeof recordsData != 'object') return;
setIsLoading?.(true);
await database.write(async () => {
await database.unsafeResetDatabase();
Expand All @@ -89,19 +107,36 @@ export class WTDBSync {
// now batch the complete recreation of database

Logger.pageLogger('WTDBSync:loadDatabase:recordsData', recordsData);
var batch = [];
Object.keys(recordsData).forEach(table => {
const _localBatch = this.prepareCreateCollectionWise(
table,
recordsData[table],
);
console.log({_localBatch, table});
batch = batch.concat(_localBatch);

const prepareCreateRecords = [];
Object.keys(recordsData).forEach(tableName => {
const collection = database.collections.get(tableName);
console.log(collection.table);
const tableRecords = recordsData[tableName];

if (
tableRecords &&
Array.isArray(tableRecords) &&
tableRecords.length > 0
) {
tableRecords.forEach(record => {
const preparedBatchRecord = this._backupToPrepareCreate(
record,
collection,
);
prepareCreateRecords.push(preparedBatchRecord);
});
}
});
Logger.pageLogger(
'WTDBSync:loadDatabase:prepareCreateRecords',
prepareCreateRecords,
);

await database.write(async () => {
await database.batch(...batch);
await database.batch(...prepareCreateRecords);
});

Logger.pageLogger('WTDBSync:loadDatabase:success');
setIsLoading?.(false);
} catch (error) {
Expand Down
1 change: 1 addition & 0 deletions js/services/alarm.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class TaskReminderService {
}
};
static removeRemindersByIDs = async ({alarmIDs}) => {
//TODO: this step throughs error in runtime
if (Array.isArray(alarmIDs) && alarmIDs.length > 0) {
alarmIDs.forEach(alarmID => {
this.removeReminder({alarmID});
Expand Down

0 comments on commit 7bfa54c

Please sign in to comment.