UNPKG

2.73 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2018, Kinvey, Inc. All rights reserved.
3 *
4 * This software is licensed to you under the Kinvey terms of service located at
5 * http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this
6 * software, you hereby accept such terms of service (and any agreement referenced
7 * therein) and agree that you have read, understand and agree to be bound by such
8 * terms of service and are of legal age to agree to such terms with Kinvey.
9 *
10 * This software contains valuable confidential and proprietary information of
11 * KINVEY, INC and is subject to applicable licensing agreements.
12 * Unauthorized reproduction, transmission or distribution of this file and its
13 * contents is a violation of applicable laws.
14 */
15
16const { OperationType } = require('./Constants');
17const { isNullOrUndefined } = require('./Utils');
18
19class FileProcessorHelper {
20 /**
21 * Groups modifiedEntities per operation type: create, update, delete.
22 * @param {Array} originalEntities A list of strings or a list of objects with a 'name' property or other property of choice.
23 * @param {Object} modifiedEntities Keys on first level are the entity's name. Ex.: { "someName": {...}, "anyName": {...} }
24 * @param {String} [prop] Property to group by. Defaults to 'name'.
25 * @returns {Object}
26 * @private
27 */
28 static groupEntitiesPerOperationType(originalEntities, modifiedEntities, prop = 'name') {
29 const entitiesToDelete = [];
30 const entitiesToCreate = {};
31 const entitiesToUpdate = [];
32
33 const entityNamesToModify = Object.keys(modifiedEntities);
34
35 originalEntities.forEach((originalEntity) => {
36 let originalName;
37 if (originalEntity && isNullOrUndefined(originalEntity[prop])) {
38 originalName = originalEntity;
39 } else {
40 originalName = originalEntity[prop];
41 }
42
43 if (!entityNamesToModify.includes(originalName)) {
44 entitiesToDelete.push(originalName);
45 } else {
46 entitiesToUpdate.push({
47 [originalName]: modifiedEntities[originalName]
48 });
49 }
50 });
51
52 entityNamesToModify.forEach((entityName) => {
53 const entityAlreadyExists = originalEntities.find((x) => {
54 if (!isNullOrUndefined(x[prop])) {
55 return x[prop] === entityName;
56 }
57
58 return x === entityName;
59 });
60
61 if (!entityAlreadyExists) {
62 entitiesToCreate[entityName] = modifiedEntities[entityName];
63 }
64 });
65
66 return {
67 [OperationType.CREATE]: entitiesToCreate,
68 [OperationType.UPDATE]: entitiesToUpdate,
69 [OperationType.DELETE]: entitiesToDelete
70 };
71 }
72}
73
74module.exports = FileProcessorHelper;