@contrail/flexplm 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1,2 +1,10 @@
1
1
  export * from './flexplm-request';
2
2
  export * from './flexplm-utils';
3
+ export * from './util/config-defaults';
4
+ export * from './util/data-converter';
5
+ export * from './util/federation';
6
+ export * from './util/flexplm-connect';
7
+ export * from './util/interfaces';
8
+ export * from './util/logger-config';
9
+ export * from './util/thumbnail-util';
10
+ export * from './util/type-utils';
package/lib/index.js CHANGED
@@ -16,3 +16,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./flexplm-request"), exports);
18
18
  __exportStar(require("./flexplm-utils"), exports);
19
+ __exportStar(require("./util/config-defaults"), exports);
20
+ __exportStar(require("./util/data-converter"), exports);
21
+ __exportStar(require("./util/federation"), exports);
22
+ __exportStar(require("./util/flexplm-connect"), exports);
23
+ __exportStar(require("./util/interfaces"), exports);
24
+ __exportStar(require("./util/logger-config"), exports);
25
+ __exportStar(require("./util/thumbnail-util"), exports);
26
+ __exportStar(require("./util/type-utils"), exports);
@@ -0,0 +1,6 @@
1
+ import { FCConfig } from './interfaces';
2
+ export declare class ConfigDefaults {
3
+ static NEED_CONFIG_VALUES: string;
4
+ static setConfigDefaults(config: any): Promise<FCConfig>;
5
+ static getConfigFile(fileId: string): Promise<any>;
6
+ }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ConfigDefaults = void 0;
13
+ const sdk_1 = require("@contrail/sdk");
14
+ const util_1 = require("@contrail/util");
15
+ class ConfigDefaults {
16
+ static setConfigDefaults(config) {
17
+ return __awaiter(this, void 0, void 0, function* () {
18
+ if (!config.apiHost || !config.userName || !config.password) {
19
+ throw new Error(ConfigDefaults.NEED_CONFIG_VALUES);
20
+ }
21
+ if ((config === null || config === void 0 ? void 0 : config.itemPreDevelopmentLifecycleStages) && !((config === null || config === void 0 ? void 0 : config.itemPreDevelopmentLifecycleStages) instanceof Array)) {
22
+ config.itemPreDevelopmentLifecycleStages = config.itemPreDevelopmentLifecycleStages.split(',');
23
+ }
24
+ const defaultConfig = {
25
+ urlContext: '/Windchill',
26
+ sendMode: {
27
+ ASYNC_PUBLISH_SEASON: 'vibeiqfile'
28
+ },
29
+ itemPreDevelopmentLifecycleStages: ['concept'],
30
+ identifierAtts: {
31
+ LCSProduct: ['itemNumber'],
32
+ LCSSeason: ['flexPLMSeasonName'],
33
+ LCSSKU: ['itemNumber']
34
+ },
35
+ csrfEndpoint: '/servlet/rest/security/csrf',
36
+ vibeEventEndpoint: '/rfa/vibeiq/vibeEvents',
37
+ payloadDefaultAsArray: true
38
+ };
39
+ const configArr = [defaultConfig];
40
+ if (config.configFile) {
41
+ const fileConfig = yield ConfigDefaults.getConfigFile(config.configFile);
42
+ configArr.push(fileConfig);
43
+ }
44
+ configArr.push(config);
45
+ const outputConfig = util_1.ObjectUtil.mergeDeep({}, ...configArr);
46
+ const uName = outputConfig.userName;
47
+ const pass = outputConfig.password;
48
+ outputConfig.userName = () => uName;
49
+ outputConfig.password = () => pass;
50
+ outputConfig['OOBvibeEventEndpoint'] = '/rfa/vibeiq/vibeEvents';
51
+ console.log('outputConfig: ' + JSON.stringify(outputConfig));
52
+ return outputConfig;
53
+ });
54
+ }
55
+ static getConfigFile(fileId) {
56
+ return __awaiter(this, void 0, void 0, function* () {
57
+ try {
58
+ const options = {
59
+ entityName: 'file',
60
+ id: fileId,
61
+ };
62
+ const file = yield new sdk_1.Entities().get(options);
63
+ if (!file) {
64
+ console.log('failed to find file with id: ' + fileId);
65
+ return {};
66
+ }
67
+ const downloadUrl = file['downloadUrl'];
68
+ if (!downloadUrl) {
69
+ console.log('file didnt have downloadUrl. fileId: ' + fileId);
70
+ return {};
71
+ }
72
+ const response = yield fetch(downloadUrl);
73
+ const config = yield response.json();
74
+ return config ? config : {};
75
+ }
76
+ catch (e) {
77
+ console.log('Error getting config file: ' + fileId + '- ' + e.message);
78
+ return {};
79
+ }
80
+ });
81
+ }
82
+ }
83
+ exports.ConfigDefaults = ConfigDefaults;
84
+ ConfigDefaults.NEED_CONFIG_VALUES = 'To connect to FlexPLM all these APP values need to be set apiHost, userName, and password';
@@ -0,0 +1,22 @@
1
+ import { FCConfig } from './interfaces';
2
+ import { MapFileUtil } from '@contrail/transform-data';
3
+ export declare class DataConverter {
4
+ private config;
5
+ private mapFileUtil;
6
+ private typeUtils;
7
+ private transformMapFile;
8
+ private useDisplayForEnumerationMatching;
9
+ private objRefCache;
10
+ constructor(config: FCConfig, mapFileUtil: MapFileUtil);
11
+ getFlexPLMObjectDataFromEvent(event: any, dataToSkip: string[]): Promise<{}>;
12
+ getFlexPLMObjectData(newData: any, dataToSkip: string[], expandObjRef: boolean): Promise<{}>;
13
+ getFlexPLMValue(prop: any, newData: any, expandObjRef: boolean): Promise<any>;
14
+ getEnumerationValue(prop: any, nd: any): any;
15
+ getObjectReferenceValue(prop: any, newData: any, expandObjRef?: boolean): Promise<any>;
16
+ getMappingClass(entity: object, mapping: any): string;
17
+ setEntityValues(entity: any, data: any, keysToSkip?: string[]): Promise<any>;
18
+ getEntityValues(objectClass: string, data: any, keysToSkip?: string[]): Promise<{}>;
19
+ getEntityValue(prop: any, data: any): Promise<any>;
20
+ setEnumerationKeys(prop: any, nd: any, matchByDisplay: any): any;
21
+ getPersistableChanges(entity: object, changes: object): object;
22
+ }
@@ -0,0 +1,341 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DataConverter = void 0;
13
+ const sdk_1 = require("@contrail/sdk");
14
+ const type_utils_1 = require("./type-utils");
15
+ const transform_data_1 = require("@contrail/transform-data");
16
+ const app_framework_1 = require("@contrail/app-framework");
17
+ const util_1 = require("@contrail/util");
18
+ class DataConverter {
19
+ constructor(config, mapFileUtil) {
20
+ this.config = config;
21
+ this.mapFileUtil = mapFileUtil;
22
+ this.useDisplayForEnumerationMatching = false;
23
+ this.objRefCache = {};
24
+ this.typeUtils = new type_utils_1.TypeUtils();
25
+ this.transformMapFile = this.config['transformMapFile'];
26
+ this.useDisplayForEnumerationMatching = this.config['dataConverter']
27
+ && this.config['dataConverter']['useDisplayForEnumerationMatching'];
28
+ }
29
+ getFlexPLMObjectDataFromEvent(event, dataToSkip) {
30
+ return __awaiter(this, void 0, void 0, function* () {
31
+ return this.getFlexPLMObjectData(event.newData, dataToSkip, true);
32
+ });
33
+ }
34
+ getFlexPLMObjectData(newData, dataToSkip, expandObjRef) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ if (app_framework_1.Logger.isDebugOn()) {
37
+ console.debug('newData: ' + JSON.stringify(newData));
38
+ }
39
+ dataToSkip = dataToSkip.concat(['updatedOn', 'updatedById', 'createdOn', 'createdById', 'modifiedAt', 'orgId', 'createdAt', 'id', 'typeId', 'workspaceId']);
40
+ const data = {};
41
+ const typeId = newData === null || newData === void 0 ? void 0 : newData.typeId;
42
+ if (!typeId) {
43
+ return;
44
+ }
45
+ data['typePath'] = newData['typePath'];
46
+ const type = yield this.typeUtils.getTypeById(typeId);
47
+ const typeProps = this.typeUtils.filterTypeProperties(type, newData);
48
+ for (const prop of typeProps) {
49
+ const slug = prop['slug'];
50
+ if (dataToSkip.includes(slug)) {
51
+ continue;
52
+ }
53
+ data[slug] = yield this.getFlexPLMValue(prop, newData, expandObjRef);
54
+ }
55
+ if (app_framework_1.Logger.isDebugOn()) {
56
+ console.debug('getFlexPLMObjectData-data: ' + JSON.stringify(data));
57
+ }
58
+ return data;
59
+ });
60
+ }
61
+ getFlexPLMValue(prop, newData, expandObjRef) {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ const propertyType = prop['propertyType'];
64
+ const slug = prop['slug'];
65
+ const nd = newData[slug];
66
+ let value;
67
+ if (['string', 'text'].includes(propertyType)) {
68
+ value = nd || '';
69
+ }
70
+ else if (['number', 'currency', 'percent', 'sequence'].includes(propertyType)) {
71
+ value = nd || 0;
72
+ }
73
+ else if ('date' === propertyType) {
74
+ if (nd) {
75
+ value = nd;
76
+ }
77
+ else {
78
+ value = null;
79
+ }
80
+ }
81
+ else if ('boolean' === propertyType) {
82
+ value = (nd) ? true : false;
83
+ }
84
+ else if ('choice' === propertyType) {
85
+ value = this.getEnumerationValue(prop, nd);
86
+ }
87
+ else if ('multi_select' === propertyType) {
88
+ value = this.getEnumerationValue(prop, nd);
89
+ }
90
+ else if ('object_reference' === propertyType) {
91
+ value = yield this.getObjectReferenceValue(prop, newData, expandObjRef);
92
+ if (app_framework_1.Logger.isDebugOn()) {
93
+ console.debug('object_reference: ' + JSON.stringify(value));
94
+ }
95
+ }
96
+ else if ('image' === propertyType) {
97
+ }
98
+ else if ('formula' === propertyType) {
99
+ value = nd;
100
+ }
101
+ else if ('json' === propertyType) {
102
+ value = nd;
103
+ }
104
+ return value;
105
+ });
106
+ }
107
+ getEnumerationValue(prop, nd) {
108
+ const propertyType = prop['propertyType'];
109
+ let value;
110
+ if (['choice', 'multi_select'].includes(propertyType)) {
111
+ const options = prop['options'];
112
+ if ('choice' === propertyType) {
113
+ if (nd) {
114
+ const option = options.find(option => option.value == nd);
115
+ if (option) {
116
+ value = Object.assign({}, option);
117
+ }
118
+ }
119
+ else {
120
+ value = {};
121
+ }
122
+ }
123
+ else if ('multi_select' === propertyType) {
124
+ value = [];
125
+ if (nd instanceof Array) {
126
+ nd.forEach(key => {
127
+ const optionObject = options.find(option => option.value == key);
128
+ if (optionObject) {
129
+ const option = Object.assign({}, optionObject);
130
+ value.push(option);
131
+ }
132
+ });
133
+ }
134
+ else if (typeof nd === 'string' && '' !== nd) {
135
+ const optionObject = options.find(option => option.value == nd);
136
+ if (optionObject) {
137
+ const option = Object.assign({}, optionObject);
138
+ value.push(option);
139
+ }
140
+ }
141
+ }
142
+ }
143
+ return value;
144
+ }
145
+ getObjectReferenceValue(prop, newData, expandObjRef = false) {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ const slug = prop['slug'];
148
+ console.debug('getObjectReferenceValue-prop: ' + slug);
149
+ let value = newData[slug];
150
+ const entityType = prop['referencedTypeRootSlug'];
151
+ const entityId = newData[slug + 'Id'];
152
+ if (!value && expandObjRef) {
153
+ if (entityId) {
154
+ if (this.objRefCache[entityId]) {
155
+ console.log('cache hit: ' + entityId);
156
+ return this.objRefCache[entityId];
157
+ }
158
+ const criteria = {
159
+ id: entityId
160
+ };
161
+ const entities = yield new sdk_1.Entities().get({
162
+ entityName: entityType,
163
+ criteria
164
+ });
165
+ value = (entities && entities[0]) ? entities[0] : undefined;
166
+ }
167
+ }
168
+ if (value) {
169
+ const unprocessedValue = value;
170
+ const objectClass = this.typeUtils.getEventObjectClass(entityType, newData);
171
+ value = yield this.getFlexPLMObjectData(value, [], false);
172
+ value['entityReference'] = entityType + ':' + entityId;
173
+ value['objectClass'] = objectClass;
174
+ value['typePath'] = unprocessedValue['typePath'];
175
+ if (this.transformMapFile) {
176
+ const wholeMap = yield this.mapFileUtil.getMapFile(this.transformMapFile);
177
+ const objClass = this.getMappingClass(unprocessedValue, wholeMap);
178
+ const mapping = yield this.mapFileUtil.getMappingSection(this.transformMapFile, objClass, 'vibe2flex');
179
+ if (mapping) {
180
+ const tasks = transform_data_1.MapFileUtil.getTransformTasks(mapping);
181
+ if (tasks.length > 0) {
182
+ const convertedArray = transform_data_1.TransformProcessor.transformData([value], tasks);
183
+ value = convertedArray[0];
184
+ }
185
+ }
186
+ }
187
+ }
188
+ else {
189
+ value = {};
190
+ }
191
+ this.objRefCache[entityId] = value;
192
+ return value;
193
+ });
194
+ }
195
+ getMappingClass(entity, mapping) {
196
+ const entityTypePath = entity['typePath'];
197
+ const typeMapKey = mapping['typeMapKey'];
198
+ let objClass = typeMapKey[entityTypePath];
199
+ const entityType = entity['entityType'];
200
+ if (!objClass) {
201
+ objClass = this.typeUtils.getEventObjectClass(entityType, entity);
202
+ }
203
+ if (!objClass) {
204
+ objClass = entityType;
205
+ }
206
+ return objClass;
207
+ }
208
+ setEntityValues(entity, data, keysToSkip = []) {
209
+ return __awaiter(this, void 0, void 0, function* () {
210
+ const type = yield this.typeUtils.getTypeById(entity.typeId);
211
+ keysToSkip = keysToSkip.concat(['updatedOn', 'updatedById', 'createdOn', 'createdById', 'modifiedAt', 'orgId', 'createdAt', 'id', 'typeId', 'workspaceId']);
212
+ let typeProps = this.typeUtils.filterTypeProperties(type, entity);
213
+ typeProps = typeProps.filter(prop => !keysToSkip.includes(prop['slug']));
214
+ const dataKeys = Object.getOwnPropertyNames(data);
215
+ typeProps = typeProps.filter(prop => dataKeys.includes(prop['slug']));
216
+ for (const prop of typeProps) {
217
+ const slug = prop['slug'];
218
+ entity[slug] = yield this.getEntityValue(prop, data);
219
+ }
220
+ return entity;
221
+ });
222
+ }
223
+ getEntityValues(objectClass, data, keysToSkip = []) {
224
+ return __awaiter(this, void 0, void 0, function* () {
225
+ const entityValues = {};
226
+ const tco = this.typeUtils.getEntityTypeClientOptions(objectClass, data);
227
+ const type = yield this.typeUtils.getByRootAndPath(tco);
228
+ const typePath = type['typePath'];
229
+ if (typePath && (typePath.startsWith('item') || typePath.startsWith('project-item'))) {
230
+ if (['LCSProduct', 'LCSProductSeasonLink'].includes(objectClass)) {
231
+ entityValues['roles'] = ['family'];
232
+ }
233
+ else {
234
+ entityValues['roles'] = ['color', 'option'];
235
+ }
236
+ }
237
+ let typeProps = this.typeUtils.filterTypeProperties(type, entityValues);
238
+ typeProps = typeProps.filter(prop => !keysToSkip.includes(prop['slug']));
239
+ for (const prop of typeProps) {
240
+ const slug = prop['slug'];
241
+ const value = yield this.getEntityValue(prop, data);
242
+ if (value) {
243
+ entityValues[slug] = value;
244
+ }
245
+ }
246
+ return entityValues;
247
+ });
248
+ }
249
+ getEntityValue(prop, data) {
250
+ return __awaiter(this, void 0, void 0, function* () {
251
+ const propertyType = prop['propertyType'];
252
+ const slug = prop['slug'];
253
+ const nd = data[slug];
254
+ let value;
255
+ if (['string', 'text'].includes(propertyType)) {
256
+ value = nd;
257
+ }
258
+ else if (['number', 'currency', 'percent', 'sequence'].includes(propertyType)) {
259
+ value = (null === nd) ? 0 : nd;
260
+ }
261
+ else if ('date' === propertyType) {
262
+ if (nd) {
263
+ const d = new Date(nd);
264
+ value = d.toISOString();
265
+ }
266
+ else {
267
+ value = null;
268
+ }
269
+ }
270
+ else if ('boolean' === propertyType) {
271
+ value = (nd) ? true : false;
272
+ }
273
+ else if ('choice' === propertyType) {
274
+ value = this.setEnumerationKeys(prop, nd, this.useDisplayForEnumerationMatching);
275
+ }
276
+ else if ('multi_select' === propertyType) {
277
+ value = this.setEnumerationKeys(prop, nd, this.useDisplayForEnumerationMatching);
278
+ }
279
+ else if ('object_reference' === propertyType) {
280
+ }
281
+ else if ('image' === propertyType) {
282
+ console.log('TODO');
283
+ }
284
+ else if ('formula' === propertyType) {
285
+ console.log('TODO');
286
+ }
287
+ else if ('json' === propertyType) {
288
+ console.log('TODO');
289
+ }
290
+ return value;
291
+ });
292
+ }
293
+ setEnumerationKeys(prop, nd, matchByDisplay) {
294
+ const propertyType = prop['propertyType'];
295
+ let value;
296
+ if (['choice', 'multi_select'].includes(propertyType)) {
297
+ const options = prop['options'];
298
+ if ('choice' === propertyType) {
299
+ if (nd) {
300
+ const matchKey = (matchByDisplay) ? 'display' : 'value';
301
+ const option = options.find(option => option[matchKey] == nd[matchKey]);
302
+ if (option) {
303
+ value = option.value;
304
+ }
305
+ }
306
+ else {
307
+ value = undefined;
308
+ }
309
+ }
310
+ else if ('multi_select' === propertyType) {
311
+ value = [];
312
+ const matchKey = (matchByDisplay) ? 'display' : 'value';
313
+ if (nd instanceof Array) {
314
+ nd.forEach(selectedOpt => {
315
+ const optionObject = options.find(option => option[matchKey] == selectedOpt[matchKey]);
316
+ if (optionObject) {
317
+ const option = optionObject.value;
318
+ value.push(option);
319
+ }
320
+ });
321
+ }
322
+ }
323
+ }
324
+ return value;
325
+ }
326
+ getPersistableChanges(entity, changes) {
327
+ const entityCompareValues = {};
328
+ for (const key of (Object.getOwnPropertyNames(changes))) {
329
+ entityCompareValues[key] = entity[key];
330
+ }
331
+ const diffs = util_1.ObjectUtil.compareDeep(entityCompareValues, changes, '');
332
+ const diffValues = {};
333
+ if (diffs && diffs.length > 0) {
334
+ for (const diff of diffs) {
335
+ diffValues[diff.propertyName] = diff.newValue;
336
+ }
337
+ }
338
+ return diffValues;
339
+ }
340
+ }
341
+ exports.DataConverter = DataConverter;
@@ -0,0 +1,15 @@
1
+ import { FederationRecord } from './interfaces';
2
+ export declare class Federation {
3
+ private CHUNK_SIZE;
4
+ getFederatedMappedRefId(entityType: string, entityId: string): Promise<string>;
5
+ createFederatedRecord(eventBody: any): Promise<any>;
6
+ getFederationRecordFromMappedRefId(mappedRefId: string): Promise<FederationRecord>;
7
+ static getEntityId(fedRecord: FederationRecord): {
8
+ entityType: string;
9
+ entityId: string;
10
+ };
11
+ getEntityFromMappedRefId(mappedRefId: string): Promise<any>;
12
+ getFederationRecordsFromIds(ids: string[]): Promise<FederationRecord[]>;
13
+ getFederationRecordsFromIdsBulk(ids: string[]): Promise<FederationRecord[]>;
14
+ splitIntoChunksByLen(arr: any, len: any): any[];
15
+ }
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Federation = void 0;
13
+ const sdk_1 = require("@contrail/sdk");
14
+ const p_limit_1 = require("p-limit");
15
+ const limit = (0, p_limit_1.default)(30);
16
+ const FED_CONFIG = {
17
+ appIdentifier: '@vibeiq/flexplm-connector',
18
+ federationSchema: 'DEFAULT'
19
+ };
20
+ class Federation {
21
+ constructor() {
22
+ this.CHUNK_SIZE = 50;
23
+ }
24
+ getFederatedMappedRefId(entityType, entityId) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const criteria = {
27
+ reference: entityType + ':' + entityId,
28
+ appIdentifier: FED_CONFIG.appIdentifier,
29
+ federationSchema: FED_CONFIG.federationSchema
30
+ };
31
+ console.log('getFederatedMappedRefId: ' + JSON.stringify(criteria));
32
+ const fedRecords = yield new sdk_1.Entities().get({
33
+ entityName: 'federation',
34
+ criteria
35
+ });
36
+ const federatedId = (fedRecords[0])
37
+ ? fedRecords[0]['mappedReference']
38
+ : '';
39
+ return federatedId;
40
+ });
41
+ }
42
+ createFederatedRecord(eventBody) {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ const itemResults = eventBody.payload;
45
+ for (let i = 0; i < itemResults.length; i++) {
46
+ if (!itemResults[i].federatedId) {
47
+ continue;
48
+ }
49
+ const payload = {
50
+ appIdentifier: FED_CONFIG.appIdentifier,
51
+ reference: itemResults[i].entityReference,
52
+ mappedReference: itemResults[i].federatedId,
53
+ federationSchema: FED_CONFIG.federationSchema
54
+ };
55
+ try {
56
+ const results = yield new sdk_1.Entities().create({ entityName: 'federation', object: payload });
57
+ return results;
58
+ }
59
+ catch (error) {
60
+ console.log('createFederatedRecord-error: ', error);
61
+ throw new Error('Error creating federation record: ' + error.message);
62
+ }
63
+ }
64
+ });
65
+ }
66
+ getFederationRecordFromMappedRefId(mappedRefId) {
67
+ return __awaiter(this, void 0, void 0, function* () {
68
+ const criteria = {
69
+ appIdentifier: FED_CONFIG.appIdentifier,
70
+ mappedReference: mappedRefId,
71
+ federationSchema: FED_CONFIG.federationSchema
72
+ };
73
+ try {
74
+ const fedRecords = yield new sdk_1.Entities().get({
75
+ entityName: 'federation',
76
+ criteria
77
+ });
78
+ return (fedRecords && fedRecords[0]) ? fedRecords[0] : undefined;
79
+ }
80
+ catch (e) {
81
+ console.log('getFederationData-error: ' + e.message);
82
+ }
83
+ return undefined;
84
+ });
85
+ }
86
+ static getEntityId(fedRecord) {
87
+ const entityString = fedRecord['reference'];
88
+ const entitySplit = entityString.split(':');
89
+ const entityType = entitySplit[0];
90
+ const entityId = entitySplit[1];
91
+ return { entityType, entityId };
92
+ }
93
+ getEntityFromMappedRefId(mappedRefId) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ const fedRecord = yield this.getFederationRecordFromMappedRefId(mappedRefId);
96
+ console.log('fedRecord: ' + JSON.stringify(fedRecord));
97
+ if (!fedRecord) {
98
+ console.log('Federation Record doesnt exist. Cant get entity!');
99
+ return;
100
+ }
101
+ const { entityType, entityId } = Federation.getEntityId(fedRecord);
102
+ const criteria = {
103
+ id: entityId
104
+ };
105
+ const entities = yield new sdk_1.Entities().get({
106
+ entityName: entityType,
107
+ criteria
108
+ });
109
+ const entity = (entities && entities[0]) ? entities[0] : undefined;
110
+ return entity;
111
+ });
112
+ }
113
+ getFederationRecordsFromIds(ids) {
114
+ return __awaiter(this, void 0, void 0, function* () {
115
+ const fedRecords = [];
116
+ for (let i = 0; i < ids.length; i++) {
117
+ const criteria = {
118
+ reference: ids[i],
119
+ appIdentifier: FED_CONFIG.appIdentifier,
120
+ federationSchema: FED_CONFIG.federationSchema
121
+ };
122
+ const recs = yield new sdk_1.Entities().get({
123
+ entityName: 'federation',
124
+ criteria
125
+ });
126
+ if (recs[0]) {
127
+ fedRecords.push(recs[0]);
128
+ }
129
+ }
130
+ return fedRecords;
131
+ });
132
+ }
133
+ getFederationRecordsFromIdsBulk(ids) {
134
+ return __awaiter(this, void 0, void 0, function* () {
135
+ const chunks = this.splitIntoChunksByLen(ids, this.CHUNK_SIZE);
136
+ const fedRecords = [];
137
+ const federatedPromises = [];
138
+ const entities = new sdk_1.Entities();
139
+ for (const chunk of chunks) {
140
+ const fedPromise = limit(() => __awaiter(this, void 0, void 0, function* () {
141
+ const criteria = {
142
+ references: chunk,
143
+ appIdentifier: FED_CONFIG.appIdentifier,
144
+ federationSchema: FED_CONFIG.federationSchema
145
+ };
146
+ const records = yield entities.get({
147
+ entityName: 'federation',
148
+ criteria
149
+ });
150
+ fedRecords.push(...records);
151
+ }));
152
+ federatedPromises.push(fedPromise);
153
+ }
154
+ yield Promise.all(federatedPromises);
155
+ return fedRecords;
156
+ });
157
+ }
158
+ splitIntoChunksByLen(arr, len) {
159
+ const chunks = [], n = arr === null || arr === void 0 ? void 0 : arr.length;
160
+ let i = 0;
161
+ while (i < n) {
162
+ chunks.push(arr.slice(i, i += len));
163
+ }
164
+ return chunks;
165
+ }
166
+ }
167
+ exports.Federation = Federation;
@@ -0,0 +1,16 @@
1
+ import { FCConfig, FlexPLMResponseData, PayloadType } from './interfaces';
2
+ export declare class FlexPLMConnect {
3
+ private config;
4
+ private vibeEventEndpoint;
5
+ payloadSendAsArray: boolean;
6
+ constructor(_config: FCConfig, endPoint?: any, payloadAsArray?: any);
7
+ private getRequestOptions;
8
+ getCSRF(): Promise<{
9
+ nonce_key: any;
10
+ nonce: any;
11
+ }>;
12
+ sendRequest(csrf: any, payload: any): Promise<Response>;
13
+ protected processRequest(payload: any): Promise<FlexPLMResponseData>;
14
+ sendToFlexPLM(payload: PayloadType): Promise<FlexPLMResponseData>;
15
+ sendMultipleToFlexPLM(payload: PayloadType[]): Promise<FlexPLMResponseData>;
16
+ }