This repository was archived by the owner on Jan 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrepository.data.js
More file actions
490 lines (424 loc) · 14.2 KB
/
repository.data.js
File metadata and controls
490 lines (424 loc) · 14.2 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import Criteria from './criteria.data.js';
import lodash from 'lodash';
export default class Repository {
/**
* @param {String} route
* @param {String} entityName
* @param {Object} httpClient
* @param {EntityHydrator} hydrator
* @param {ChangesetGenerator} changesetGenerator
* @param {EntityFactory} entityFactory
* @param {Object} options
*/
constructor(
route,
entityName,
httpClient,
hydrator,
changesetGenerator,
entityFactory,
options
) {
this.route = route;
this.entityName = entityName;
this.httpClient = httpClient;
this.hydrator = hydrator;
this.changesetGenerator = changesetGenerator;
this.entityFactory = entityFactory;
this.options = options;
}
get schema() {
return Shopware.EntityDefinition.get(this.entityName);
}
/**
* Sends a search request to the server to find entity ids for the provided criteria.
* @param {Criteria} criteria
* @param {Object} context
* @returns {Promise}
*/
searchIds(criteria, context) {
const headers = this.buildHeaders(context);
const url = `/search-ids${this.route}`;
return this.httpClient
.post(url, criteria.parse(), { headers, version: this.options.version })
.then((response) => {
return response.data;
});
}
/**
* Sends a search request for the repository entity.
* @param {Criteria} criteria
* @param {Object} context
* @returns {Promise}
*/
search(criteria, context) {
const headers = this.buildHeaders(context);
const url = `/search${this.route}`;
console.log(this.options);
return this.httpClient
.post(url, criteria.parse(), {
headers,
version: this.options.version
})
.then((response) => {
return this.hydrator.hydrateSearchResult(this.route, this.entityName, response, context, criteria);
});
}
/**
* Short hand to fetch a single entity from the server
* @param {String} id
* @param {Object} context
* @param {Criteria} criteria
* @returns {Promise}
*/
get(id, context, criteria) {
criteria = criteria || new Criteria();
criteria.setIds([id]);
return this.search(criteria, context).then((result) => {
return result.get(id);
});
}
/**
* Detects all entity changes and send the changes to the server.
* If the entity is marked as new, the repository will send a POST create. Updates will be send as PATCH request.
* Deleted associations will be send as additional request
*
* @param {Entity} entity
* @param {Object} context
* @returns {Promise<any>}
*/
save(entity, context) {
const { changes, deletionQueue } = this.changesetGenerator.generate(entity);
return this.sendDeletions(deletionQueue, context)
.then(() => this.sendChanges(entity, changes, context));
}
/**
* Clones an existing entity
*
* @param {String} entityId
* @param {Object} context
* @param {Object} overwrites
* @returns {Promise<T>}
*/
clone(entityId, context, overwrites) {
if (!entityId) {
return Promise.reject(new Error('Missing required argument: id'));
}
return this.httpClient
.post(`/_action/clone${this.route}/${entityId}`, { overwrites }, {
headers: this.buildHeaders(context),
version: this.options.version
})
.then((response) => {
return response.data;
});
}
/**
* Detects if the entity or the relations has remaining changes which are not synchronized with the server
* @param {Entity} entity
* @returns {boolean}
*/
hasChanges(entity) {
const { changes, deletionQueue } = this.changesetGenerator.generate(entity);
return changes !== null || deletionQueue.length > 0;
}
/**
* Detects changes of all provided entities and send the changes to the server
*
* @param {Array} entities
* @param {Object} context
* @returns {Promise<any[]>}
*/
saveAll(entities, context) {
const promises = [];
entities.forEach((entity) => {
promises.push(this.save(entity, context));
});
return Promise.all(promises);
}
/**
* Detects changes of all provided entities and send the changes to the server
*
* @param {Array} entities
* @param {Object} context
* @param {Boolean} failOnError
* @returns {Promise<any[]>}
*/
sync(entities, context, failOnError = true) {
const { changeset, deletions } = this.getSyncChangeset(entities);
return this.sendDeletions(deletions, context)
.then(() => this.sendUpserts(changeset, failOnError, context));
}
/**
* Detects changes of the provided entity and resets its first-level attributes to its origin state
*
* @param {Object} entity
*/
discard(entity) {
if (!entity) {
return;
}
const { changes } = this.changesetGenerator.generate(entity);
if (!changes) {
return;
}
const origin = entity.getOrigin();
Object.keys(changes).forEach((changedField) => {
entity[changedField] = origin[changedField];
});
}
/**
* @private
* @param changeset
* @param failOnError
* @param context
* @returns {*}
*/
sendUpserts(changeset, failOnError, context) {
if (changeset.length <= 0) {
return Promise.resolve();
}
const payload = changeset.map(({ changes }) => changes);
const headers = this.buildHeaders(context);
headers['fail-on-error'] = failOnError;
return this.httpClient.post(
'_action/sync',
{
[this.entityName]: {
entity: this.entityName,
action: 'upsert',
payload
}
},
{ headers, version: this.options.version }
).then(({ data }) => {
if (data.success === false) {
throw data;
}
return Promise.resolve();
}).catch((errorResponse) => {
throw errorResponse;
});
}
/**
* @private
* @param errorResponse
* @returns {Array}
*/
getSyncErrors(errorResponse) {
const operation = errorResponse.response.data.data[this.entityName];
return operation.result.reduce((acc, result) => {
acc.push(...result.errors);
return acc;
}, []);
}
/**
* @private
* @param entities
* @returns {*}
*/
getSyncChangeset(entities) {
return entities.reduce((acc, entity) => {
const { changes, deletionQueue } = this.changesetGenerator.generate(entity);
acc.deletions.push(...deletionQueue);
if (changes === null) {
return acc;
}
const pkData = this.changesetGenerator.getPrimaryKeyData(entity);
Object.assign(changes, pkData);
acc.changeset.push({ entity, changes });
return acc;
}, { changeset: [], deletions: [] });
}
/**
* Sends a create request for a many to many relation. This can only be used for many to many repository
* where the base route contains already the owner key, e.g. /product/{id}/categories
* The provided id contains the associated entity id.
*
* @param {String} id
* @param {Object} context
* @returns {Promise}
*/
assign(id, context) {
const headers = this.buildHeaders(context);
return this.httpClient.post(`${this.route}`, { id }, { headers, version: this.options.version });
}
/**
* Sends a delete request for the provided id.
* @param {String} id
* @param {Object} context
* @returns {Promise}
*/
delete(id, context) {
const headers = this.buildHeaders(context);
const url = `${this.route}/${id}`;
return this.httpClient.delete(url, { headers, version: this.options.version })
.catch((errorResponse) => {
throw errorResponse;
});
}
/**
* Sends a delete request for a set of ids
* @param {Array} ids
* @param {Object} context
* @returns {Promise}
*/
syncDeleted(ids, context) {
const headers = this.buildHeaders(context);
headers['fail-on-error'] = true;
const payload = ids.map((id) => {
return { id };
});
return this.httpClient.post(
'_action/sync',
{
[this.entityName]: {
entity: this.entityName,
action: 'delete',
payload
}
},
{ headers, version: this.options.version }
).then(({ data }) => {
if (data.success === false) {
throw data;
}
return Promise.resolve();
}).catch((errorResponse) => {
throw errorResponse;
});
}
/**
* Creates a new entity for the local schema.
* To Many association are initialed with a collection with the corresponding remote api route
*
* @param {Object} context
* @param {String|null} id
* @returns {Entity}
*/
create(context, id) {
return this.entityFactory.create(this.entityName, id, context);
}
/**
* Creates a new version for the provided entity id. If no version id provided, the server
* will generate a new version id.
* If no version name provided, the server names the new version with `draft %date%`.
*
* @param {string} entityId
* @param {Object} context
* @param {String|null} versionId
* @param {String|null} versionName
* @returns {Promise}
*/
createVersion(entityId, context, versionId = null, versionName = null) {
const headers = this.buildHeaders(context);
const params = {};
if (versionId) {
params.versionId = versionId;
}
if (versionName) {
params.versionName = versionName;
}
const url = `_action/version/${this.entityName.replace(/_/g, '-')}/${entityId}`;
return this.httpClient.post(url, params, { headers, version: this.options.version }).then((response) => {
return { ...context, ...{ versionId: response.data.versionId } };
});
}
/**
* Sends a request to the server to merge all changes of the provided version id.
* The changes are squashed into a single change and the remaining version will be removed.
* @param {String} versionId
* @param {Object} context
* @returns {Promise}
*/
mergeVersion(versionId, context) {
const headers = this.buildHeaders(context);
const url = `_action/version/merge/${this.entityName.replace(/_/g, '-')}/${versionId}`;
return this.httpClient.post(url, {}, { headers, version: this.options.version });
}
/**
* Deletes the provided version from the server. All changes to this version are reverted
* @param {String} entityId
* @param {String} versionId
* @param {Object} context
* @returns {Promise}
*/
deleteVersion(entityId, versionId, context) {
const headers = this.buildHeaders(context);
const url = `/_action/version/${versionId}/${this.entityName.replace(/_/g, '-')}/${entityId}`;
return this.httpClient.post(url, {}, { headers, version: this.options.version });
}
/**
* @private
* @param {Entity} entity
* @param {Object} changes
* @param {Object} context
* @returns {*}
*/
sendChanges(entity, changes, context) {
const headers = this.buildHeaders(context);
if (entity.isNew()) {
changes = changes || {};
Object.assign(changes, { id: entity.id });
return this.httpClient.post(`${this.route}`, changes, { headers, version: this.options.version })
.catch((errorResponse) => {
throw errorResponse;
});
}
if (typeof changes === 'undefined' || changes === null) {
return Promise.resolve();
}
return this.httpClient.patch(`${this.route}/${entity.id}`, changes, { headers, version: this.options.version })
.catch((errorResponse) => {
throw errorResponse;
});
}
/**
* Process the deletion queue
* @param {Array} queue
* @param {Object} context
* @returns {Promise}
*/
sendDeletions(queue, context) {
const headers = this.buildHeaders(context);
const requests = queue.map((deletion) => {
return this.httpClient.delete(`${deletion.route}/${deletion.key}`, { headers, version: this.options.version })
.catch((errorResponse) => {
throw errorResponse;
});
});
return Promise.all(requests);
}
/**
* Builds the request header for read and write operations
* @param {Object} context
* @returns {Object}
*/
buildHeaders(context) {
const compatibility = lodash.hasOwnProperty(this.options, 'compatibility') ? this.options.compatibility : true;
let headers = {
Accept: 'application/vnd.api+json',
Authorization: `Bearer ${context.authToken.access}`,
'Content-Type': 'application/json'
};
if (context.languageId) {
headers = Object.assign(
{ 'sw-language-id': context.languageId },
headers
);
}
if (context.versionId) {
headers = Object.assign(
{ 'sw-version-id': context.versionId },
headers
);
}
if (context.inheritance) {
headers = Object.assign(
{ 'sw-inheritance': context.inheritance },
headers
);
}
return headers;
}
}