@@ -144,6 +144,9 @@ class DataSyncController {
144
144
}
145
145
}
146
146
147
+ const APPEND_NEW_RECORD = 0 ;
148
+ const PREPEND_NEW_RECORD = 1 ;
149
+
147
150
class DataSubscription {
148
151
constructor ( query ) {
149
152
if ( typeof query !== "object" || ! ( 'table' in query ) ) {
@@ -164,6 +167,21 @@ class DataSubscription {
164
167
165
168
this . getRecords = this . getRecords . bind ( this ) ;
166
169
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 ;
167
185
}
168
186
169
187
async createOnServer ( ) {
@@ -251,7 +269,8 @@ class DataSubscription {
251
269
}
252
270
253
271
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 ] ;
255
274
this . updateSubscribers ( ) ;
256
275
}
257
276
0 commit comments