Skip to content

Commit

Permalink
DataSync: Prepend new records if the query is sorted newest first
Browse files Browse the repository at this point in the history
  • Loading branch information
mpscholten committed Jan 26, 2022
1 parent 5f67c9c commit 06de6df
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion lib/IHP/DataSync/ihp-datasync.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@ class DataSyncController {
}
}

const APPEND_NEW_RECORD = 0;
const PREPEND_NEW_RECORD = 1;

class DataSubscription {
constructor(query) {
if (typeof query !== "object" || !('table' in query)) {
Expand All @@ -164,6 +167,21 @@ class DataSubscription {

this.getRecords = this.getRecords.bind(this);
this.subscribe = this.subscribe.bind(this);

// When a new record is inserted, do we put it at the end or at the beginning?
this.newRecordBehaviour = this.detectNewRecordBehaviour();
}

detectNewRecordBehaviour() {
// If the query is ordered by the createdAt column, and the latest is at the top
// we want to prepend new record
const isOrderByCreatedAtDesc = this.query.orderByClause.length > 0 && this.query.orderByClause[0].orderByColumn === 'createdAt' && this.query.orderByClause[0].orderByColumn === 'createdAt';

if (isOrderByCreatedAtDesc) {
return PREPEND_NEW_RECORD;
}

return APPEND_NEW_RECORD;
}

async createOnServer() {
Expand Down Expand Up @@ -251,7 +269,8 @@ class DataSubscription {
}

onCreate(newRecord) {
this.records = [...this.records, newRecord];
const shouldAppend = this.newRecordBehaviour === APPEND_NEW_RECORD;
this.records = shouldAppend ? [...this.records, newRecord] : [newRecord, ...this.records];
this.updateSubscribers();
}

Expand Down

0 comments on commit 06de6df

Please sign in to comment.