Skip to content

Commit c83c810

Browse files
Implemented nested global fields (#1717)
* Implemented nested global fields * Passed api version by default 3.2 * Updated the implementation as same as the content type * Updated code * Removed unused code * Updated display text. * Fixed PR comments
1 parent 51428a6 commit c83c810

File tree

5 files changed

+101
-32
lines changed

5 files changed

+101
-32
lines changed

packages/contentstack-export/src/export/modules/global-fields.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export default class GlobalFieldsExport extends BaseClass {
6060
if (skip) {
6161
this.qs.skip = skip;
6262
}
63-
let globalFieldsFetchResponse = await this.stackAPIClient.globalField().query(this.qs).find();
63+
let globalFieldsFetchResponse = await this.stackAPIClient.globalField({api_version: '3.2'}).query(this.qs).find();
6464
if (Array.isArray(globalFieldsFetchResponse.items) && globalFieldsFetchResponse.items.length > 0) {
6565
this.sanitizeAttribs(globalFieldsFetchResponse.items);
6666
skip += this.globalFieldsConfig.limit || 100;

packages/contentstack-import/src/import/modules/base-class.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,8 @@ export default abstract class BaseClass {
315315
return this.stack.contentType().create(apiData).then(onSuccess).catch(onReject);
316316
case 'update-cts':
317317
return apiData.update().then(onSuccess).catch(onReject);
318+
case 'create-gfs':
319+
return this.stack.globalField({api_version: '3.2'}).create(apiData).then(onSuccess).catch(onReject);
318320
case 'update-gfs':
319321
return apiData.update().then(onSuccess).catch(onReject);
320322
case 'create-environments':

packages/contentstack-import/src/import/modules/content-types.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ export default class ContentTypesImport extends BaseClass {
232232
log(this.importConfig, `Updated the global field ${uid} with content type references`, 'info');
233233
};
234234
const onReject = ({ error, apiData: { uid } = undefined }: any) => {
235-
log(this.importConfig, `failed to update the global field '${uid}' ${formatError(error)}`, 'error');
235+
log(this.importConfig, `Failed to update the global field '${uid}' ${formatError(error)}`, 'error');
236236
};
237237
return await this.makeConcurrentCall({
238238
processName: 'Update pending global fields',
@@ -266,8 +266,9 @@ export default class ContentTypesImport extends BaseClass {
266266
this.importConfig.preserveStackVersion,
267267
this.installedExtensions,
268268
);
269-
apiOptions.apiData = globalField;
270-
const globalFieldPayload = this.stack.globalField(uid);
269+
const globalFieldPayload = this.stack.globalField(
270+
uid, { api_version: '3.2' },
271+
);
271272
Object.assign(globalFieldPayload, cloneDeep(globalField));
272273
apiOptions.apiData = globalFieldPayload;
273274
return apiOptions;

packages/contentstack-import/src/import/modules/global-fields.ts

Lines changed: 67 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@
66
*/
77

88
import * as path from 'path';
9-
import { isEmpty, cloneDeep } from 'lodash';
9+
import { isEmpty, cloneDeep, map, find } from 'lodash';
1010
import { cliux, sanitizePath } from '@contentstack/cli-utilities';
11-
import { GlobalFieldData } from '@contentstack/management/types/stack/globalField';
11+
import { GlobalFieldData, GlobalField } from '@contentstack/management/types/stack/globalField';
1212
import { fsUtil, log, formatError, fileHelper, lookupExtension, removeReferenceFields } from '../../utils';
1313
import { ImportConfig, ModuleClassParams } from '../../types';
1414
import BaseClass, { ApiOptions } from './base-class';
15+
import { gfSchemaTemplate } from '../../utils/global-field-helper';
16+
1517

1618
export default class ImportGlobalFields extends BaseClass {
1719
private gFsMapperPath: string;
@@ -73,8 +75,12 @@ export default class ImportGlobalFields extends BaseClass {
7375
((await fsUtil.readFile(this.marketplaceAppMapperPath)) as any) || { extension_uid: {} }
7476
).extension_uid;
7577

76-
await this.importGFs();
77-
fsUtil.writeFile(this.gFsPendingPath, this.pendingGFs);
78+
await this.seedGFs();
79+
if (this.seedGFs?.length) fsUtil.writeFile(this.gFsPendingPath, this.pendingGFs);
80+
log(this.importConfig, 'Created Global Fields', 'success');
81+
82+
await this.updateGFs();
83+
log(this.importConfig, 'Updated Global Fields', 'success');
7884

7985
if (this.importConfig.replaceExisting && this.existingGFs.length > 0) {
8086
await this.replaceGFs().catch((error: Error) => {
@@ -85,46 +91,79 @@ export default class ImportGlobalFields extends BaseClass {
8591
log(this.config, 'Global fields import has been completed!', 'info');
8692
}
8793

88-
async importGFs() {
94+
async seedGFs(): Promise<any> {
8995
const onSuccess = ({ response: globalField, apiData: { uid } = undefined }: any) => {
9096
this.createdGFs.push(globalField);
9197
this.gFsUidMapper[uid] = globalField;
92-
fsUtil.writeFile(this.gFsUidMapperPath, this.gFsUidMapper);
93-
log(this.config, 'Global field ' + uid + ' created successfully', 'success');
98+
log(this.importConfig, `Global field ${globalField.uid} created successfully`, 'success');
9499
};
95100
const onReject = ({ error, apiData: globalField = undefined }: any) => {
96-
const uid = globalField.uid;
101+
const uid = globalField?.uid;
97102
if (error?.errors?.title) {
98103
if (this.importConfig.replaceExisting) {
99104
this.existingGFs.push(globalField);
100105
}
101106
if (!this.importConfig.skipExisting) {
102-
log(this.importConfig, `Global fields '${uid}' already exist`, 'info');
107+
log(this.importConfig, `Global fields '${globalField?.global_field?.uid}' already exist`, 'info');
103108
}
104109
} else {
105110
log(this.importConfig, `Global fields '${uid}' failed to import`, 'error');
106111
log(this.importConfig, formatError(error), 'error');
107112
this.failedGFs.push({ uid });
108113
}
109114
};
115+
return await this.makeConcurrentCall({
116+
processName: 'Import global fields',
117+
apiContent: this.gFs,
118+
apiParams: {
119+
serializeData: this.serializeGFs.bind(this),
120+
reject: onReject.bind(this),
121+
resolve: onSuccess.bind(this),
122+
entity: 'create-gfs',
123+
includeParamOnCompletion: true,
124+
},
125+
concurrencyLimit: this.reqConcurrency,
126+
});
127+
}
110128

111-
return await this.makeConcurrentCall(
112-
{
113-
processName: 'Import global fields',
114-
apiContent: this.gFs,
115-
apiParams: {
116-
reject: onReject.bind(this),
117-
resolve: onSuccess.bind(this),
118-
entity: 'create-gfs',
119-
includeParamOnCompletion: true,
120-
},
121-
concurrencyLimit: this.reqConcurrency,
129+
/**
130+
* @method serializeGFs
131+
* @param {ApiOptions} apiOptions ApiOptions
132+
* @returns {ApiOptions} ApiOptions
133+
*/
134+
serializeGFs(apiOptions: ApiOptions): ApiOptions {
135+
const { apiData: globalField } = apiOptions;
136+
const updatedGF = cloneDeep(gfSchemaTemplate);
137+
updatedGF.global_field.uid = globalField.uid;
138+
updatedGF.global_field.title = globalField.title;
139+
apiOptions.apiData = updatedGF;
140+
return apiOptions;
141+
}
142+
143+
async updateGFs(): Promise<any> {
144+
const onSuccess = ({ response: globalField, apiData: { uid } = undefined }: any) => {
145+
log(this.importConfig, `Updated the global field ${uid}`, 'info');
146+
};
147+
const onReject = ({ error, apiData: { uid } = undefined }: any) => {
148+
log(this.importConfig, `Failed to update the global field '${uid}' ${formatError(error)}`, 'error');
149+
};
150+
151+
return await this.makeConcurrentCall({
152+
processName: 'Update Global Fields',
153+
apiContent: this.gFs,
154+
apiParams: {
155+
reject: onReject.bind(this),
156+
resolve: onSuccess.bind(this),
157+
entity: 'update-gfs',
158+
includeParamOnCompletion: true,
122159
},
123-
this.createGFs.bind(this),
160+
concurrencyLimit: this.reqConcurrency,
161+
},
162+
this.updateSerializedGFs.bind(this),
124163
);
125164
}
126165

127-
async createGFs({
166+
async updateSerializedGFs({
128167
apiParams,
129168
element: globalField,
130169
isLastRequest,
@@ -141,16 +180,16 @@ export default class ImportGlobalFields extends BaseClass {
141180
this.pendingGFs.push(globalField.uid);
142181
}
143182
return this.stack
144-
.globalField()
145-
.create({ global_field: globalField as GlobalFieldData })
146-
.then((response) => {
183+
.globalField(globalField.uid, { api_version: '3.2' })
184+
.update({ global_field: globalField })
185+
.then((response: GlobalField) => {
147186
apiParams.resolve({
148187
response,
149188
apiData: globalField,
150189
});
151190
resolve(true);
152191
})
153-
.catch((error) => {
192+
.catch((error: unknown) => {
154193
apiParams.reject({
155194
error,
156195
apiData: globalField,
@@ -193,13 +232,13 @@ export default class ImportGlobalFields extends BaseClass {
193232
}
194233

195234
/**
196-
* @method serializeUpdateGFs
235+
* @method serializeReplaceGFs
197236
* @param {ApiOptions} apiOptions ApiOptions
198237
* @returns {ApiOptions} ApiOptions
199238
*/
200239
serializeReplaceGFs(apiOptions: ApiOptions): ApiOptions {
201240
const { apiData: globalField } = apiOptions;
202-
const globalFieldPayload = this.stack.globalField(globalField.uid);
241+
const globalFieldPayload = this.stack.globalField(globalField.uid, { api_version: '3.2' });
203242
Object.assign(globalFieldPayload, cloneDeep(globalField), {
204243
stackHeaders: globalFieldPayload.stackHeaders,
205244
});
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Global field utiles
3+
* schema template
4+
* remove reference fields
5+
* suppress mandatory fields
6+
*/
7+
8+
export const gfSchemaTemplate = {
9+
"global_field": {
10+
"title": "Seed",
11+
"uid": "",
12+
"schema": [
13+
{
14+
"display_name": "Title",
15+
"uid": "title",
16+
"data_type": "text",
17+
"field_metadata": {
18+
"_default": true
19+
},
20+
"unique": false,
21+
"mandatory": true,
22+
"multiple": false
23+
}
24+
],
25+
"description": "Seed "
26+
}
27+
};

0 commit comments

Comments
 (0)