-
Notifications
You must be signed in to change notification settings - Fork 2k
/
cart-synchronizer.js
264 lines (216 loc) · 7.25 KB
/
cart-synchronizer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/**
* External dependencies
*/
import { assign, flowRight, flow, get } from 'lodash';
import Dispatcher from 'calypso/dispatcher';
import { TRANSACTION_STEP_SET } from 'calypso/lib/transaction/action-types';
import debugFactory from 'debug';
/**
* Internal dependencies
*/
import Emitter from 'calypso/lib/mixins/emitter';
import { preprocessCartForServer, fillInAllCartItemAttributes } from 'calypso/lib/cart-values';
import { addCartItem } from 'calypso/lib/cart-values/cart-items';
import productsListFactory from 'calypso/lib/products-list';
const productsList = productsListFactory();
/**
* Internal dependencies
*/
const debug = debugFactory( 'calypso:cart-data:cart-synchronizer' );
function preprocessCartFromServer( cart ) {
return assign( {}, cart, {
client_metadata: createClientMetadata(),
products: castProductIDsToNumbers( cart.products ),
tax: castTaxObject( cart.tax ), // cast tax.location to object
} );
}
// Add a server response date so we can distinguish between carts with the
// same attributes from the server.
//
// NOTE: This object has underscored keys to match the rest of the attributes
// in the `CartValue object`.
function createClientMetadata() {
return { last_server_response_date: new Date().toISOString() };
}
// FIXME: Temporary fix to cast string product IDs to numbers. There is a bug
// with the API where it sometimes returns product IDs as strings.
function castProductIDsToNumbers( cartItems ) {
return cartItems.map( function ( item ) {
return assign( {}, item, { product_id: parseInt( item.product_id, 10 ) } );
} );
}
// The API is returning arrays for location that mess with our
// immutability-helper functions, so we need to make sure to convert
// these to objects. We should be able to remove this after that's fixed.
function castTaxObject( tax ) {
return {
...tax,
location: { ...get( tax, 'location' ) }, // cast location to object
};
}
function CartSynchronizer( cartKey, wpcom ) {
if ( ! ( this instanceof CartSynchronizer ) ) {
return new CartSynchronizer( cartKey, wpcom );
}
this._cartKey = cartKey;
this._wpcom = wpcom;
this._latestValue = null;
this._hasLoadedFromServer = false;
this._activeRequest = null;
this._queuedChanges = null;
this._paused = false;
this.dispatchToken = Dispatcher.register( this.handleDispatch.bind( this ) );
}
Emitter( CartSynchronizer.prototype );
CartSynchronizer.prototype.handleDispatch = function ( { action } ) {
switch ( action.type ) {
case TRANSACTION_STEP_SET:
if ( action.step.first && ! action.step.last ) {
this.pause();
}
if ( action.step.last && ! action.step.first ) {
this.resume();
}
}
};
CartSynchronizer.prototype.update = function ( changeFunction ) {
if ( ! this._hasLoadedFromServer ) {
// If we haven't loaded any data from the server yet, it's possible that
// the local data could completely overwrite the existing data. This would
// happen if we applied the change to the local data and sent it to the
// server immediately at this point.
//
// When the program first runs, the most up-to-date version of the data is
// on the server. We need to fetch from the server at least once to end up
// with a consistent state when we apply our local changes. The strategy
// here is to queue the changes until the first request has completed, then
// proceed as normal.
this._enqueueChange( changeFunction );
return;
}
if ( this._activeRequest && this._activeRequest.state !== 'canceled' ) {
this._activeRequest.state = 'canceled';
}
this._latestValue = changeFunction( this._latestValue );
this._performRequest( 'update', this._postToServer.bind( this ) );
};
CartSynchronizer.prototype.pause = function () {
this._paused = true;
};
CartSynchronizer.prototype.resume = function () {
this._paused = false;
};
CartSynchronizer.prototype._enqueueChange = function ( changeFunction ) {
if ( this._queuedChanges ) {
this._queuedChanges = flowRight( changeFunction, this._queuedChanges );
} else {
this._queuedChanges = changeFunction;
}
};
CartSynchronizer.prototype._processQueuedChanges = function () {
if ( ! this._queuedChanges ) {
return;
}
if ( this._activeRequest && this._activeRequest.state !== 'canceled' ) {
this._activeRequest.state = 'canceled';
}
this._latestValue = this._queuedChanges( this._latestValue );
this._queuedChanges = null;
this._performRequest( 'update', this._postToServer.bind( this ) );
};
CartSynchronizer.prototype._postToServer = function ( callback ) {
this._wpcom.setCart(
this._cartKey,
preprocessCartForServer( this._latestValue ),
function ( error, newValue ) {
if ( error ) {
callback( error );
return;
}
callback( null, preprocessCartFromServer( newValue ) );
}
);
};
CartSynchronizer.prototype._poll = function () {
this._performRequest( 'poll', this._getFromServer.bind( this ) );
};
CartSynchronizer.prototype._pollFromLocalStorage = function () {
const newCartItemsToAdd = JSON.parse( window.localStorage.getItem( 'shoppingCart' ) || '[]' );
const addtoCart = flow( ...newCartItemsToAdd.map( ( cartItem ) => addCartItem( cartItem ) ) );
const changeFunction = ( cart ) => {
return fillInAllCartItemAttributes( addtoCart( cart ), productsList.get() );
};
if ( ! this._latestValue ) {
const initialCart = {
cart_key: this._cartKey,
products: [],
temporary: 'no-user' === this._cartKey,
};
this._latestValue = changeFunction( initialCart );
}
this._performRequest( 'poll', this._postToServer.bind( this ) );
};
CartSynchronizer.prototype.fetch = function () {
this._performRequest( 'fetch', this._getFromServer.bind( this ) );
};
CartSynchronizer.prototype._getFromServer = function ( callback ) {
this._wpcom.getCart( this._cartKey, function ( error, newValue ) {
if ( error ) {
callback( error );
return;
}
callback( null, preprocessCartFromServer( newValue ) );
} );
};
let requestCounter = 0;
CartSynchronizer.prototype._performRequest = function ( type, requestFunction ) {
if ( type === 'poll' && this._paused ) {
return;
}
if ( this._activeRequest && this._activeRequest.state === 'pending' ) {
return false;
}
const request = {
id: requestCounter++,
type: type,
state: 'pending',
};
this._activeRequest = request;
debug( request.id + ': starting ' + request.type );
requestFunction(
function onResponse( error, newValue ) {
if ( request.state === 'canceled' ) {
debug( request.id + ': canceled ' + request.type );
return;
}
if ( error ) {
throw error;
}
debug( request.id + ': finishing ' + request.type );
this._latestValue = newValue;
request.state = 'completed';
if ( ! this._hasLoadedFromServer ) {
this._processQueuedChanges();
this._hasLoadedFromServer = true;
}
this.emit( 'change' );
}.bind( this )
);
};
CartSynchronizer.prototype.getLatestValue = function () {
if ( ! this._hasLoadedFromServer ) {
throw new Error( 'Value cannot be read before fetching from the server at least once.' );
}
return this._latestValue;
};
CartSynchronizer.prototype.hasLoadedFromServer = function () {
return this._hasLoadedFromServer;
};
CartSynchronizer.prototype.hasPendingServerUpdates = function () {
return (
this._activeRequest &&
this._activeRequest.type === 'update' &&
this._activeRequest.state === 'pending'
);
};
export default CartSynchronizer;