@@ -106,6 +106,43 @@ export function createSortedStateAdapter<T>(selectId: any, sort: any): any {
106106 }
107107 }
108108
109+ function upsertOneMutably ( update : Update < T > , state : R ) : DidMutate ;
110+ function upsertOneMutably ( update : any , state : any ) : DidMutate {
111+ return upsertManyMutably ( [ update ] , state ) ;
112+ }
113+
114+ function upsertManyMutably ( updates : Update < T > [ ] , state : R ) : DidMutate ;
115+ function upsertManyMutably ( updates : any [ ] , state : any ) : DidMutate {
116+ const added : T [ ] = [ ] ;
117+ const updated : Update < T > [ ] = [ ] ;
118+
119+ for ( let index in updates ) {
120+ const update = updates [ index ] ;
121+ if ( update . id in state . entities ) {
122+ updated . push ( update ) ;
123+ } else {
124+ added . push ( {
125+ ...update . changes ,
126+ id : update . id ,
127+ } ) ;
128+ }
129+ }
130+
131+ const didMutateByUpdated = updateManyMutably ( updated , state ) ;
132+ const didMutateByAdded = addManyMutably ( added , state ) ;
133+
134+ switch ( true ) {
135+ case didMutateByAdded === DidMutate . None &&
136+ didMutateByUpdated === DidMutate . None :
137+ return DidMutate . None ;
138+ case didMutateByAdded === DidMutate . Both ||
139+ didMutateByUpdated === DidMutate . Both :
140+ return DidMutate . Both ;
141+ default :
142+ return DidMutate . EntitiesOnly ;
143+ }
144+ }
145+
109146 function merge ( models : T [ ] , state : R ) : void ;
110147 function merge ( models : any [ ] , state : any ) : void {
111148 models . sort ( sort ) ;
@@ -147,8 +184,10 @@ export function createSortedStateAdapter<T>(selectId: any, sort: any): any {
147184 removeAll,
148185 addOne : createStateOperator ( addOneMutably ) ,
149186 updateOne : createStateOperator ( updateOneMutably ) ,
187+ upsertOne : createStateOperator ( upsertOneMutably ) ,
150188 addAll : createStateOperator ( addAllMutably ) ,
151189 addMany : createStateOperator ( addManyMutably ) ,
152190 updateMany : createStateOperator ( updateManyMutably ) ,
191+ upsertMany : createStateOperator ( upsertManyMutably ) ,
153192 } ;
154193}
0 commit comments