diff --git a/lib/IHP/DataSync/ihp-datasync.js b/lib/IHP/DataSync/ihp-datasync.js index 4bffaf451..89c403da7 100644 --- a/lib/IHP/DataSync/ihp-datasync.js +++ b/lib/IHP/DataSync/ihp-datasync.js @@ -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)) { @@ -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() { @@ -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(); }