Skip to content

Commit 06de6df

Browse files
committed
DataSync: Prepend new records if the query is sorted newest first
1 parent 5f67c9c commit 06de6df

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

lib/IHP/DataSync/ihp-datasync.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ class DataSyncController {
144144
}
145145
}
146146

147+
const APPEND_NEW_RECORD = 0;
148+
const PREPEND_NEW_RECORD = 1;
149+
147150
class DataSubscription {
148151
constructor(query) {
149152
if (typeof query !== "object" || !('table' in query)) {
@@ -164,6 +167,21 @@ class DataSubscription {
164167

165168
this.getRecords = this.getRecords.bind(this);
166169
this.subscribe = this.subscribe.bind(this);
170+
171+
// When a new record is inserted, do we put it at the end or at the beginning?
172+
this.newRecordBehaviour = this.detectNewRecordBehaviour();
173+
}
174+
175+
detectNewRecordBehaviour() {
176+
// If the query is ordered by the createdAt column, and the latest is at the top
177+
// we want to prepend new record
178+
const isOrderByCreatedAtDesc = this.query.orderByClause.length > 0 && this.query.orderByClause[0].orderByColumn === 'createdAt' && this.query.orderByClause[0].orderByColumn === 'createdAt';
179+
180+
if (isOrderByCreatedAtDesc) {
181+
return PREPEND_NEW_RECORD;
182+
}
183+
184+
return APPEND_NEW_RECORD;
167185
}
168186

169187
async createOnServer() {
@@ -251,7 +269,8 @@ class DataSubscription {
251269
}
252270

253271
onCreate(newRecord) {
254-
this.records = [...this.records, newRecord];
272+
const shouldAppend = this.newRecordBehaviour === APPEND_NEW_RECORD;
273+
this.records = shouldAppend ? [...this.records, newRecord] : [newRecord, ...this.records];
255274
this.updateSubscribers();
256275
}
257276

0 commit comments

Comments
 (0)