@stackbit/cms-core 0.0.17 → 0.0.19-alpha.1
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/dist/annotator/html.d.ts +1 -0
- package/dist/annotator/html.d.ts.map +1 -0
- package/dist/annotator/index.d.ts +3 -2
- package/dist/annotator/index.d.ts.map +1 -0
- package/dist/annotator/react.d.ts +1 -0
- package/dist/annotator/react.d.ts.map +1 -0
- package/dist/common/common-schema.d.ts +3 -10
- package/dist/common/common-schema.d.ts.map +1 -0
- package/dist/common/common-schema.js +3 -4
- package/dist/common/common-schema.js.map +1 -1
- package/dist/consts.d.ts +1 -0
- package/dist/consts.d.ts.map +1 -0
- package/dist/content-source-interface.d.ts +324 -0
- package/dist/content-source-interface.d.ts.map +1 -0
- package/dist/content-source-interface.js +28 -0
- package/dist/content-source-interface.js.map +1 -0
- package/dist/content-store-types.d.ts +328 -0
- package/dist/content-store-types.d.ts.map +1 -0
- package/dist/content-store-types.js +3 -0
- package/dist/content-store-types.js.map +1 -0
- package/dist/content-store.d.ts +207 -0
- package/dist/content-store.d.ts.map +1 -0
- package/dist/content-store.js +1743 -0
- package/dist/content-store.js.map +1 -0
- package/dist/encoder.d.ts +36 -7
- package/dist/encoder.d.ts.map +1 -0
- package/dist/encoder.js +63 -40
- package/dist/encoder.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +37 -11
- package/dist/index.js.map +1 -1
- package/dist/stackbit/index.d.ts +7 -3
- package/dist/stackbit/index.d.ts.map +1 -0
- package/dist/stackbit/index.js +13 -10
- package/dist/stackbit/index.js.map +1 -1
- package/dist/utils/index.d.ts +8 -7
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/schema-utils.d.ts +3 -2
- package/dist/utils/schema-utils.d.ts.map +1 -0
- package/dist/utils/timer.d.ts +18 -0
- package/dist/utils/timer.d.ts.map +1 -0
- package/dist/utils/timer.js +36 -0
- package/dist/utils/timer.js.map +1 -0
- package/package.json +8 -4
- package/src/common/common-schema.ts +12 -0
- package/src/content-source-interface.ts +468 -0
- package/src/content-store-types.ts +416 -0
- package/src/content-store.ts +2233 -0
- package/src/{encoder.js → encoder.ts} +55 -17
- package/src/index.ts +10 -0
- package/src/stackbit/{index.js → index.ts} +5 -9
- package/src/utils/timer.ts +42 -0
- package/dist/utils/lazy-poller.d.ts +0 -21
- package/dist/utils/lazy-poller.js +0 -56
- package/dist/utils/lazy-poller.js.map +0 -1
- package/src/common/common-schema.js +0 -14
- package/src/index.js +0 -13
- package/src/utils/lazy-poller.ts +0 -74
|
@@ -0,0 +1,2233 @@
|
|
|
1
|
+
import _ from 'lodash';
|
|
2
|
+
import slugify from 'slugify';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import sanitizeFilename from 'sanitize-filename';
|
|
5
|
+
import {
|
|
6
|
+
Config,
|
|
7
|
+
extendConfig,
|
|
8
|
+
Field,
|
|
9
|
+
FieldList,
|
|
10
|
+
FieldListItems,
|
|
11
|
+
FieldListProps,
|
|
12
|
+
FieldModelProps,
|
|
13
|
+
FieldObjectProps,
|
|
14
|
+
FieldSpecificProps,
|
|
15
|
+
loadConfigFromDir,
|
|
16
|
+
Model
|
|
17
|
+
} from '@stackbit/sdk';
|
|
18
|
+
import { mapPromise, omitByNil } from '@stackbit/utils';
|
|
19
|
+
import * as CSITypes from './content-source-interface';
|
|
20
|
+
import { isLocalizedField } from './content-source-interface';
|
|
21
|
+
import * as ContentStoreTypes from './content-store-types';
|
|
22
|
+
import { IMAGE_MODEL } from './common/common-schema';
|
|
23
|
+
import { Timer } from './utils/timer';
|
|
24
|
+
|
|
25
|
+
export interface ContentSourceOptions {
|
|
26
|
+
logger: ContentStoreTypes.Logger;
|
|
27
|
+
userLogger: ContentStoreTypes.Logger;
|
|
28
|
+
localDev: boolean;
|
|
29
|
+
stackbitYamlDir: string;
|
|
30
|
+
contentSources: CSITypes.ContentSourceInterface[];
|
|
31
|
+
onSchemaChangeCallback: () => void;
|
|
32
|
+
onContentChangeCallback: (contentChanges: ContentStoreTypes.ContentChangeResult) => void;
|
|
33
|
+
handleConfigAssets: (config: Config) => Promise<Config>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface ContentSourceData {
|
|
37
|
+
id: string;
|
|
38
|
+
instance: CSITypes.ContentSourceInterface;
|
|
39
|
+
type: string;
|
|
40
|
+
projectId: string;
|
|
41
|
+
models: Model[];
|
|
42
|
+
modelMap: Record<string, Model>;
|
|
43
|
+
locales?: CSITypes.Locale[];
|
|
44
|
+
defaultLocaleCode?: string;
|
|
45
|
+
csiDocuments: CSITypes.Document[];
|
|
46
|
+
csiDocumentMap: Record<string, CSITypes.Document>;
|
|
47
|
+
documents: ContentStoreTypes.Document[];
|
|
48
|
+
documentMap: Record<string, ContentStoreTypes.Document>;
|
|
49
|
+
csiAssets: CSITypes.Asset[];
|
|
50
|
+
csiAssetMap: Record<string, CSITypes.Asset>;
|
|
51
|
+
assets: ContentStoreTypes.Asset[];
|
|
52
|
+
assetMap: Record<string, ContentStoreTypes.Asset>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export class ContentStore {
|
|
56
|
+
private readonly contentSources: CSITypes.ContentSourceInterface[];
|
|
57
|
+
private readonly logger: ContentStoreTypes.Logger;
|
|
58
|
+
private readonly userLogger: ContentStoreTypes.Logger;
|
|
59
|
+
private readonly localDev: boolean;
|
|
60
|
+
private readonly stackbitYamlDir: string; // TODO: remove stackbitYamlDir, ContentStore should not be aware of filesystem, instead pass autoreloading Config object
|
|
61
|
+
private readonly onSchemaChangeCallback: () => void;
|
|
62
|
+
private readonly onContentChangeCallback: (contentChanges: ContentStoreTypes.ContentChangeResult) => void;
|
|
63
|
+
private readonly handleConfigAssets: (config: Config) => Promise<Config>;
|
|
64
|
+
private contentSourceDataById: Record<string, ContentSourceData> = {};
|
|
65
|
+
private contentUpdatesWatchTimer: Timer;
|
|
66
|
+
private rawStackbitConfig: any;
|
|
67
|
+
private presets?: Record<string, any>;
|
|
68
|
+
|
|
69
|
+
constructor(options: ContentSourceOptions) {
|
|
70
|
+
this.logger = options.logger.createLogger({ label: 'content-store' });
|
|
71
|
+
this.userLogger = options.userLogger.createLogger({ label: 'content-store' });
|
|
72
|
+
this.localDev = options.localDev;
|
|
73
|
+
this.stackbitYamlDir = options.stackbitYamlDir; // TODO: remove stackbitYamlDir, ContentStore should not be aware of filesystem, instead pass autoreloading Config object
|
|
74
|
+
this.contentSources = options.contentSources;
|
|
75
|
+
this.onSchemaChangeCallback = options.onSchemaChangeCallback;
|
|
76
|
+
this.onContentChangeCallback = options.onContentChangeCallback;
|
|
77
|
+
this.handleConfigAssets = options.handleConfigAssets;
|
|
78
|
+
this.contentUpdatesWatchTimer = new Timer({ timerCallback: () => this.handleTimerTimeout(), logger: this.logger });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async init(): Promise<void> {
|
|
82
|
+
this.logger.debug('init');
|
|
83
|
+
this.rawStackbitConfig = await this.loadStackbitConfig();
|
|
84
|
+
|
|
85
|
+
this.logger.debug('init => load content source data');
|
|
86
|
+
for (const contentSourceInstance of this.contentSources) {
|
|
87
|
+
await this.loadContentSourceData({ contentSourceInstance, init: true });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
this.contentUpdatesWatchTimer.startTimer();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async reset() {
|
|
94
|
+
this.logger.debug('reset');
|
|
95
|
+
|
|
96
|
+
this.contentUpdatesWatchTimer.stopTimer();
|
|
97
|
+
this.rawStackbitConfig = await this.loadStackbitConfig();
|
|
98
|
+
|
|
99
|
+
this.logger.debug('reset => load content source data');
|
|
100
|
+
for (const contentSourceInstance of this.contentSources) {
|
|
101
|
+
await this.loadContentSourceData({ contentSourceInstance, init: false });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
this.contentUpdatesWatchTimer.startTimer();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* This method is called when contentUpdatesWatchTimer receives timeout.
|
|
109
|
+
* It then notifies all content sources to stop watching for content changes.
|
|
110
|
+
*/
|
|
111
|
+
handleTimerTimeout() {
|
|
112
|
+
for (const contentSourceInstance of this.contentSources) {
|
|
113
|
+
contentSourceInstance.stopWatchingContentUpdates();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* This method is called when user interacts with Stackbit application.
|
|
119
|
+
* It is used to reset contentUpdatesWatchTimer. When the timer is over
|
|
120
|
+
* all content sources are notified to stop watching for content updates.
|
|
121
|
+
*/
|
|
122
|
+
async keepAlive() {
|
|
123
|
+
if (!this.contentUpdatesWatchTimer.isRunning()) {
|
|
124
|
+
this.logger.debug('keepAlive => contentUpdatesWatchTimer is not running => load content source data');
|
|
125
|
+
for (const contentSourceInstance of this.contentSources) {
|
|
126
|
+
await this.loadContentSourceData({ contentSourceInstance, init: false });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
this.contentUpdatesWatchTimer.resetTimer();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* This method is called when a content source notifies Stackbit of models
|
|
134
|
+
* changes via webhook. When this happens, all content source data
|
|
135
|
+
*
|
|
136
|
+
* For example, Contentful notifies Stackbit of any content-type changes via
|
|
137
|
+
* special webhook.
|
|
138
|
+
*
|
|
139
|
+
* @param contentSourceId
|
|
140
|
+
*/
|
|
141
|
+
async onContentSourceSchemaChange({ contentSourceId }: { contentSourceId: string }) {
|
|
142
|
+
this.logger.debug('onContentSourceSchemaChange', { contentSourceId });
|
|
143
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
144
|
+
await this.loadContentSourceData({
|
|
145
|
+
contentSourceInstance: contentSourceData.instance,
|
|
146
|
+
init: false
|
|
147
|
+
});
|
|
148
|
+
this.onSchemaChangeCallback();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async onFilesChange(
|
|
152
|
+
updatedFiles: string[]
|
|
153
|
+
): Promise<{ stackbitConfigUpdated?: boolean; schemaChanged?: boolean; contentChanges: ContentStoreTypes.ContentChangeResult }> {
|
|
154
|
+
this.logger.debug('onFilesChange');
|
|
155
|
+
|
|
156
|
+
const stackbitConfigUpdated = _.some(updatedFiles, (filePath) => isStackbitConfigFile(filePath));
|
|
157
|
+
this.logger.debug(`stackbitConfigUpdated: ${stackbitConfigUpdated}`);
|
|
158
|
+
if (stackbitConfigUpdated) {
|
|
159
|
+
this.rawStackbitConfig = await this.loadStackbitConfig();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
let someContentSourceSchemaUpdated = false;
|
|
163
|
+
const contentChanges: ContentStoreTypes.ContentChangeResult = {
|
|
164
|
+
updatedDocuments: [],
|
|
165
|
+
updatedAssets: [],
|
|
166
|
+
deletedDocuments: [],
|
|
167
|
+
deletedAssets: []
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
for (const contentSourceInstance of this.contentSources) {
|
|
171
|
+
const contentSourceId = getContentSourceIdForContentSource(contentSourceInstance);
|
|
172
|
+
this.logger.debug(`call onFilesChange for contentSource: ${contentSourceId}`);
|
|
173
|
+
const { schemaChanged, contentChangeEvent } = contentSourceInstance.onFilesChange?.({ updatedFiles: updatedFiles }) ?? {};
|
|
174
|
+
this.logger.debug(`schemaChanged: ${schemaChanged}, has contentChangeEvent: ${!!contentChangeEvent}`);
|
|
175
|
+
// if schema is changed, there is no need to return contentChanges
|
|
176
|
+
// because schema changes reloads everything and implies content changes
|
|
177
|
+
if (stackbitConfigUpdated || schemaChanged) {
|
|
178
|
+
if (schemaChanged) {
|
|
179
|
+
someContentSourceSchemaUpdated = true;
|
|
180
|
+
}
|
|
181
|
+
await this.loadContentSourceData({ contentSourceInstance, init: false });
|
|
182
|
+
} else if (contentChangeEvent) {
|
|
183
|
+
const contentChangeResult = this.onContentChange(contentSourceId, contentChangeEvent);
|
|
184
|
+
contentChanges.updatedDocuments = contentChanges.updatedDocuments.concat(contentChangeResult.updatedDocuments);
|
|
185
|
+
contentChanges.updatedAssets = contentChanges.updatedAssets.concat(contentChangeResult.updatedAssets);
|
|
186
|
+
contentChanges.deletedDocuments = contentChanges.deletedDocuments.concat(contentChangeResult.deletedDocuments);
|
|
187
|
+
contentChanges.deletedAssets = contentChanges.deletedAssets.concat(contentChangeResult.deletedAssets);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
stackbitConfigUpdated,
|
|
193
|
+
schemaChanged: someContentSourceSchemaUpdated || stackbitConfigUpdated,
|
|
194
|
+
contentChanges: contentChanges
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async loadStackbitConfig() {
|
|
199
|
+
this.logger.debug('loadStackbitConfig');
|
|
200
|
+
// TODO: use esbuild to watch for stackbit.config.js changes and notify
|
|
201
|
+
// the content-store via onStackbitConfigChange with updated rawConfig
|
|
202
|
+
const { config, errors } = await loadConfigFromDir({ dirPath: this.stackbitYamlDir });
|
|
203
|
+
for (const error of errors) {
|
|
204
|
+
this.userLogger.warn(error.message);
|
|
205
|
+
}
|
|
206
|
+
if (!config) {
|
|
207
|
+
this.userLogger.error(`could not load stackbit config`);
|
|
208
|
+
}
|
|
209
|
+
return config;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async loadContentSourceData({ contentSourceInstance, init }: { contentSourceInstance: CSITypes.ContentSourceInterface; init: boolean }) {
|
|
213
|
+
// TODO: defer loading content if content is already loading for a specific content source
|
|
214
|
+
|
|
215
|
+
// TODO: optimize: cache raw responses from contentSource
|
|
216
|
+
// e.g.: getModels(), getDocuments(), getAssets()
|
|
217
|
+
// ana use the cached response to remap documents when only stackbitConfig changes
|
|
218
|
+
|
|
219
|
+
const contentSourceId = getContentSourceIdForContentSource(contentSourceInstance);
|
|
220
|
+
this.logger.debug('loadContentSourceData', { contentSourceId, init });
|
|
221
|
+
|
|
222
|
+
if (init) {
|
|
223
|
+
await contentSourceInstance.init({
|
|
224
|
+
logger: this.logger,
|
|
225
|
+
userLogger: this.userLogger,
|
|
226
|
+
localDev: this.localDev
|
|
227
|
+
});
|
|
228
|
+
} else {
|
|
229
|
+
contentSourceInstance.stopWatchingContentUpdates();
|
|
230
|
+
await contentSourceInstance.reset();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const csModels = await contentSourceInstance.getModels();
|
|
234
|
+
const locales = await contentSourceInstance?.getLocales();
|
|
235
|
+
const result = await extendConfig({ dirPath: this.stackbitYamlDir, config: this.rawStackbitConfig, externalModels: csModels });
|
|
236
|
+
const config = await this.handleConfigAssets(result.config);
|
|
237
|
+
const models = config.models;
|
|
238
|
+
const modelMap = _.keyBy(models, 'name');
|
|
239
|
+
const defaultLocaleCode = locales?.find((locale) => locale.default)?.code;
|
|
240
|
+
|
|
241
|
+
for (const error of result.errors) {
|
|
242
|
+
this.userLogger.warn(error.message);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// TODO: load presets externally from config, and create additional map
|
|
246
|
+
// that maps presetIds by model name instead of storing that map inside every model
|
|
247
|
+
this.presets = config.presets;
|
|
248
|
+
|
|
249
|
+
const csiDocuments = await contentSourceInstance.getDocuments({ modelMap });
|
|
250
|
+
const csiAssets = await contentSourceInstance.getAssets();
|
|
251
|
+
const csiDocumentMap = _.keyBy(csiDocuments, 'id');
|
|
252
|
+
const csiAssetMap = _.keyBy(csiAssets, 'id');
|
|
253
|
+
|
|
254
|
+
const contentStoreDocuments = mapCSIDocumentsToStoreDocuments({
|
|
255
|
+
csiDocuments,
|
|
256
|
+
contentSourceInstance,
|
|
257
|
+
modelMap,
|
|
258
|
+
defaultLocaleCode
|
|
259
|
+
});
|
|
260
|
+
const contentStoreAssets = mapCSIAssetsToStoreAssets({
|
|
261
|
+
csiAssets,
|
|
262
|
+
contentSourceInstance,
|
|
263
|
+
defaultLocaleCode
|
|
264
|
+
});
|
|
265
|
+
const documentMap = _.keyBy(contentStoreDocuments, 'srcObjectId');
|
|
266
|
+
const assetMap = _.keyBy(contentStoreAssets, 'srcObjectId');
|
|
267
|
+
|
|
268
|
+
this.logger.debug('loaded content source data', {
|
|
269
|
+
contentSourceId,
|
|
270
|
+
locales,
|
|
271
|
+
defaultLocaleCode,
|
|
272
|
+
modelCount: models.length,
|
|
273
|
+
documentCount: contentStoreDocuments.length,
|
|
274
|
+
assetCount: contentStoreAssets.length
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
this.contentSourceDataById[contentSourceId] = {
|
|
278
|
+
id: contentSourceId,
|
|
279
|
+
type: contentSourceInstance.getContentSourceType(),
|
|
280
|
+
projectId: contentSourceInstance.getProjectId(),
|
|
281
|
+
instance: contentSourceInstance,
|
|
282
|
+
locales: locales,
|
|
283
|
+
defaultLocaleCode: defaultLocaleCode,
|
|
284
|
+
models: models,
|
|
285
|
+
modelMap: modelMap,
|
|
286
|
+
csiDocuments: csiDocuments,
|
|
287
|
+
csiDocumentMap: csiDocumentMap,
|
|
288
|
+
documents: contentStoreDocuments,
|
|
289
|
+
documentMap: documentMap,
|
|
290
|
+
csiAssets: csiAssets,
|
|
291
|
+
csiAssetMap: csiAssetMap,
|
|
292
|
+
assets: contentStoreAssets,
|
|
293
|
+
assetMap: assetMap
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
contentSourceInstance.startWatchingContentUpdates({
|
|
297
|
+
getModelMap: () => {
|
|
298
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
299
|
+
return contentSourceData.modelMap;
|
|
300
|
+
},
|
|
301
|
+
getDocument({ documentId }: { documentId: string }) {
|
|
302
|
+
return csiDocumentMap[documentId];
|
|
303
|
+
},
|
|
304
|
+
getAsset({ assetId }: { assetId: string }) {
|
|
305
|
+
return csiAssetMap[assetId];
|
|
306
|
+
},
|
|
307
|
+
onContentChange: (contentChangeEvent: CSITypes.ContentChangeEvent) => {
|
|
308
|
+
this.logger.debug('content source called onContentChange', { contentSourceId });
|
|
309
|
+
const result = this.onContentChange(contentSourceId, contentChangeEvent);
|
|
310
|
+
this.onContentChangeCallback(result);
|
|
311
|
+
},
|
|
312
|
+
onSchemaChange: async () => {
|
|
313
|
+
this.logger.debug('content source called onSchemaChange', { contentSourceId });
|
|
314
|
+
await this.loadContentSourceData({
|
|
315
|
+
contentSourceInstance: contentSourceInstance,
|
|
316
|
+
init: false
|
|
317
|
+
});
|
|
318
|
+
this.onSchemaChangeCallback();
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
onContentChange(contentSourceId: string, contentChangeEvent: CSITypes.ContentChangeEvent): ContentStoreTypes.ContentChangeResult {
|
|
324
|
+
// TODO: prevent content change process for contentSourceId if loading content is in progress
|
|
325
|
+
|
|
326
|
+
this.logger.debug('onContentChange', {
|
|
327
|
+
contentSourceId,
|
|
328
|
+
documentCount: contentChangeEvent.documents.length,
|
|
329
|
+
assetCount: contentChangeEvent.assets.length,
|
|
330
|
+
deletedDocumentCount: contentChangeEvent.deletedDocumentIds.length,
|
|
331
|
+
deletedAssetCount: contentChangeEvent.deletedAssetIds.length
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
const result: ContentStoreTypes.ContentChangeResult = {
|
|
335
|
+
updatedDocuments: [],
|
|
336
|
+
updatedAssets: [],
|
|
337
|
+
deletedDocuments: [],
|
|
338
|
+
deletedAssets: []
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
342
|
+
|
|
343
|
+
// update contentSourceData with deleted documents
|
|
344
|
+
contentChangeEvent.deletedDocumentIds.forEach((docId) => {
|
|
345
|
+
// delete document from documents map
|
|
346
|
+
delete contentSourceData.documentMap[docId];
|
|
347
|
+
delete contentSourceData.csiDocumentMap[docId];
|
|
348
|
+
|
|
349
|
+
// delete document from document array
|
|
350
|
+
const index = contentSourceData.documents.findIndex((document) => document.srcObjectId === docId);
|
|
351
|
+
if (index !== -1) {
|
|
352
|
+
// the indexes of documents and csiDocuments are always the same as they are always updated at the same time
|
|
353
|
+
contentSourceData.documents.splice(index, 1);
|
|
354
|
+
contentSourceData.csiDocuments.splice(index, 1);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
result.deletedDocuments.push({
|
|
358
|
+
srcType: contentSourceData.type,
|
|
359
|
+
srcProjectId: contentSourceData.projectId,
|
|
360
|
+
srcObjectId: docId
|
|
361
|
+
});
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
// update contentSourceData with deleted assets
|
|
365
|
+
contentChangeEvent.deletedAssetIds.forEach((assetId) => {
|
|
366
|
+
// delete document from asset map
|
|
367
|
+
delete contentSourceData.assetMap[assetId];
|
|
368
|
+
delete contentSourceData.csiAssetMap[assetId];
|
|
369
|
+
|
|
370
|
+
// delete document from asset array
|
|
371
|
+
const index = contentSourceData.assets.findIndex((asset) => asset.srcObjectId === assetId);
|
|
372
|
+
if (index !== -1) {
|
|
373
|
+
// the indexes of assets and csiAssets are always the same as they are always updated at the same time
|
|
374
|
+
contentSourceData.assets.splice(index, 1);
|
|
375
|
+
contentSourceData.csiAssets.splice(index, 1);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
result.deletedAssets.push({
|
|
379
|
+
srcType: contentSourceData.type,
|
|
380
|
+
srcProjectId: contentSourceData.projectId,
|
|
381
|
+
srcObjectId: assetId
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
// map csi documents and assets to content store documents and assets
|
|
386
|
+
const documents = mapCSIDocumentsToStoreDocuments({
|
|
387
|
+
csiDocuments: contentChangeEvent.documents,
|
|
388
|
+
contentSourceInstance: contentSourceData.instance,
|
|
389
|
+
modelMap: contentSourceData.modelMap,
|
|
390
|
+
defaultLocaleCode: contentSourceData.defaultLocaleCode
|
|
391
|
+
});
|
|
392
|
+
const assets = mapCSIAssetsToStoreAssets({
|
|
393
|
+
csiAssets: contentChangeEvent.assets,
|
|
394
|
+
contentSourceInstance: contentSourceData.instance,
|
|
395
|
+
defaultLocaleCode: contentSourceData.defaultLocaleCode
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
// update contentSourceData with new or updated documents and assets
|
|
399
|
+
Object.assign(contentSourceData.csiDocumentMap, _.keyBy(contentChangeEvent.documents, 'id'));
|
|
400
|
+
Object.assign(contentSourceData.csiAssets, _.keyBy(contentChangeEvent.assets, 'id'));
|
|
401
|
+
Object.assign(contentSourceData.documentMap, _.keyBy(documents, 'srcObjectId'));
|
|
402
|
+
Object.assign(contentSourceData.assetMap, _.keyBy(assets, 'srcObjectId'));
|
|
403
|
+
|
|
404
|
+
for (let idx = 0; idx < documents.length; idx++) {
|
|
405
|
+
// the indexes of mapped documents and documents from changeEvent are the same
|
|
406
|
+
const document = documents[idx]!;
|
|
407
|
+
const csiDocument = contentChangeEvent.documents[idx]!;
|
|
408
|
+
const dataIndex = contentSourceData.documents.findIndex((existingDoc) => existingDoc.srcObjectId === document.srcObjectId);
|
|
409
|
+
if (dataIndex === -1) {
|
|
410
|
+
contentSourceData.documents.push(document);
|
|
411
|
+
contentSourceData.csiDocuments.push(csiDocument);
|
|
412
|
+
} else {
|
|
413
|
+
// the indexes of documents and csiDocuments are always the same as they are always updated at the same time
|
|
414
|
+
contentSourceData.documents.splice(dataIndex, 1, document);
|
|
415
|
+
contentSourceData.csiDocuments.splice(dataIndex, 1, csiDocument);
|
|
416
|
+
}
|
|
417
|
+
result.updatedDocuments.push({
|
|
418
|
+
srcType: contentSourceData.type,
|
|
419
|
+
srcProjectId: contentSourceData.projectId,
|
|
420
|
+
srcObjectId: document.srcObjectId
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
for (let idx = 0; idx < assets.length; idx++) {
|
|
425
|
+
// the indexes of mapped assets and assets from changeEvent are the same
|
|
426
|
+
const asset = assets[idx]!;
|
|
427
|
+
const csiAsset = contentChangeEvent.assets[idx]!;
|
|
428
|
+
const index = contentSourceData.assets.findIndex((existingAsset) => existingAsset.srcObjectId === asset.srcObjectId);
|
|
429
|
+
if (index === -1) {
|
|
430
|
+
contentSourceData.assets.push(asset);
|
|
431
|
+
contentSourceData.csiAssets.push(csiAsset);
|
|
432
|
+
} else {
|
|
433
|
+
// the indexes of assets and csiAssets are always the same as they are always updated at the same time
|
|
434
|
+
contentSourceData.assets.splice(index, 1, asset);
|
|
435
|
+
contentSourceData.csiAssets.splice(index, 1, csiAsset);
|
|
436
|
+
}
|
|
437
|
+
result.updatedAssets.push({
|
|
438
|
+
srcType: contentSourceData.type,
|
|
439
|
+
srcProjectId: contentSourceData.projectId,
|
|
440
|
+
srcObjectId: asset.srcObjectId
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
return result;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
getModels(): Record<string, Record<string, Record<string, Model>>> {
|
|
448
|
+
return _.reduce(
|
|
449
|
+
this.contentSourceDataById,
|
|
450
|
+
(result: Record<string, Record<string, Record<string, Model>>>, contentSourceData) => {
|
|
451
|
+
const contentSourceType = contentSourceData.instance.getContentSourceType();
|
|
452
|
+
const srcProjectId = contentSourceData.instance.getProjectId();
|
|
453
|
+
_.set(result, [contentSourceType, srcProjectId], contentSourceData.modelMap);
|
|
454
|
+
return result;
|
|
455
|
+
},
|
|
456
|
+
{}
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
getLocales(): string[] {
|
|
461
|
+
return _.reduce(
|
|
462
|
+
this.contentSourceDataById,
|
|
463
|
+
(result: string[], contentSourceData) => {
|
|
464
|
+
const locales = (contentSourceData.locales ?? []).map((locale) => locale.code);
|
|
465
|
+
return result.concat(locales);
|
|
466
|
+
},
|
|
467
|
+
[]
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
getPresets(): Record<string, any> {
|
|
472
|
+
return this.presets ?? {};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
getContentSourceEnvironment({ srcProjectId, srcType }: { srcProjectId: string; srcType: string }): string {
|
|
476
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
477
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
478
|
+
return contentSourceData.instance.getProjectEnvironment();
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
hasAccess({ srcType, srcProjectId, user }: { srcType: string; srcProjectId: string; user?: ContentStoreTypes.User }): Promise<boolean> {
|
|
482
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
483
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
484
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
485
|
+
return contentSourceData.instance.hasAccess({ userContext });
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
hasChanges({
|
|
489
|
+
srcType,
|
|
490
|
+
srcProjectId,
|
|
491
|
+
documents
|
|
492
|
+
}: {
|
|
493
|
+
srcType?: string;
|
|
494
|
+
srcProjectId?: string;
|
|
495
|
+
documents?: { srcType: string; srcProjectId: string; srcObjectId: string }[];
|
|
496
|
+
}): {
|
|
497
|
+
hasChanges: boolean;
|
|
498
|
+
changedObjects: {
|
|
499
|
+
srcType: string;
|
|
500
|
+
srcProjectId: string;
|
|
501
|
+
srcObjectId: string;
|
|
502
|
+
}[];
|
|
503
|
+
} {
|
|
504
|
+
let result: (ContentStoreTypes.Document | ContentStoreTypes.Asset)[];
|
|
505
|
+
if (srcType && srcProjectId) {
|
|
506
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
507
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
508
|
+
result = [...contentSourceData.documents, ...contentSourceData.assets];
|
|
509
|
+
} else if (documents && documents.length > 0) {
|
|
510
|
+
const documentsBySourceId = _.groupBy(documents, (document) => getContentSourceId(document.srcType, document.srcProjectId));
|
|
511
|
+
result = _.reduce(
|
|
512
|
+
documentsBySourceId,
|
|
513
|
+
(result: (ContentStoreTypes.Document | ContentStoreTypes.Asset)[], documents, contentSourceId) => {
|
|
514
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
515
|
+
for (const document of documents) {
|
|
516
|
+
if (document.srcObjectId in contentSourceData.documentMap) {
|
|
517
|
+
result.push(contentSourceData.documentMap[document.srcObjectId]!);
|
|
518
|
+
} else if (document.srcObjectId in contentSourceData.assetMap) {
|
|
519
|
+
result.push(contentSourceData.assetMap[document.srcObjectId]!);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return result;
|
|
523
|
+
},
|
|
524
|
+
[]
|
|
525
|
+
);
|
|
526
|
+
} else {
|
|
527
|
+
result = _.reduce(
|
|
528
|
+
this.contentSourceDataById,
|
|
529
|
+
(result: (ContentStoreTypes.Document | ContentStoreTypes.Asset)[], contentSourceData) => {
|
|
530
|
+
return result.concat(contentSourceData.documents, contentSourceData.assets);
|
|
531
|
+
},
|
|
532
|
+
[]
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
const changedDocuments = result.filter((document) => document.status === 'added' || document.status === 'modified');
|
|
536
|
+
return {
|
|
537
|
+
hasChanges: !_.isEmpty(changedDocuments),
|
|
538
|
+
changedObjects: changedDocuments.map((item) => ({
|
|
539
|
+
srcType: item.srcType,
|
|
540
|
+
srcProjectId: item.srcProjectId,
|
|
541
|
+
srcObjectId: item.srcObjectId
|
|
542
|
+
}))
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
getDocument({
|
|
547
|
+
srcDocumentId,
|
|
548
|
+
srcProjectId,
|
|
549
|
+
srcType
|
|
550
|
+
}: {
|
|
551
|
+
srcDocumentId: string;
|
|
552
|
+
srcProjectId: string;
|
|
553
|
+
srcType: string;
|
|
554
|
+
}): ContentStoreTypes.Document | undefined {
|
|
555
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
556
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
557
|
+
return contentSourceData.documentMap[srcDocumentId];
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
getDocuments(): ContentStoreTypes.Document[] {
|
|
561
|
+
return _.reduce(
|
|
562
|
+
this.contentSourceDataById,
|
|
563
|
+
(documents: ContentStoreTypes.Document[], contentSourceData) => {
|
|
564
|
+
return documents.concat(contentSourceData.documents);
|
|
565
|
+
},
|
|
566
|
+
[]
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
getAsset({ srcAssetId, srcProjectId, srcType }: { srcAssetId: string; srcProjectId: string; srcType: string }): ContentStoreTypes.Asset | undefined {
|
|
571
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
572
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
573
|
+
return contentSourceData.assetMap[srcAssetId];
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
getAssets(): ContentStoreTypes.Asset[] {
|
|
577
|
+
return _.reduce(
|
|
578
|
+
this.contentSourceDataById,
|
|
579
|
+
(assets: ContentStoreTypes.Asset[], contentSourceData) => {
|
|
580
|
+
return assets.concat(contentSourceData.assets);
|
|
581
|
+
},
|
|
582
|
+
[]
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
getLocalizedApiObjects({ locale }: { locale?: string }): ContentStoreTypes.APIObject[] {
|
|
587
|
+
return _.reduce(
|
|
588
|
+
this.contentSourceDataById,
|
|
589
|
+
(objects: ContentStoreTypes.APIObject[], contentSourceData) => {
|
|
590
|
+
locale = locale ?? contentSourceData.defaultLocaleCode;
|
|
591
|
+
const documentObjects = mapDocumentsToLocalizedApiObjects(contentSourceData.documents, locale);
|
|
592
|
+
const imageObjects = mapAssetsToLocalizedApiImages(contentSourceData.assets, locale);
|
|
593
|
+
return objects.concat(documentObjects, imageObjects);
|
|
594
|
+
},
|
|
595
|
+
[]
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
getApiAssets({
|
|
600
|
+
srcType,
|
|
601
|
+
srcProjectId,
|
|
602
|
+
pageSize = 20,
|
|
603
|
+
pageNum = 1,
|
|
604
|
+
searchQuery
|
|
605
|
+
}: { srcType?: string; srcProjectId?: string; pageSize?: number; pageNum?: number; searchQuery?: string } = {}): {
|
|
606
|
+
assets: ContentStoreTypes.APIAsset[];
|
|
607
|
+
pageSize: number;
|
|
608
|
+
pageNum: number;
|
|
609
|
+
totalPages: number;
|
|
610
|
+
} {
|
|
611
|
+
let assets: ContentStoreTypes.APIAsset[];
|
|
612
|
+
if (srcProjectId && srcType) {
|
|
613
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
614
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
615
|
+
assets = mapStoreAssetsToAPIAssets(contentSourceData.assets, contentSourceData.defaultLocaleCode);
|
|
616
|
+
} else {
|
|
617
|
+
assets = _.reduce(
|
|
618
|
+
this.contentSourceDataById,
|
|
619
|
+
(result: ContentStoreTypes.APIAsset[], contentSourceData) => {
|
|
620
|
+
const assets = mapStoreAssetsToAPIAssets(contentSourceData.assets, contentSourceData.defaultLocaleCode);
|
|
621
|
+
return result.concat(assets);
|
|
622
|
+
},
|
|
623
|
+
[]
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
let filteredFiles = assets;
|
|
628
|
+
if (searchQuery) {
|
|
629
|
+
const sanitizedSearchQuery = sanitizeFilename(searchQuery).toLowerCase();
|
|
630
|
+
filteredFiles = assets.filter((asset) => asset.fileName && path.basename(asset.fileName).toLowerCase().includes(sanitizedSearchQuery));
|
|
631
|
+
}
|
|
632
|
+
const sortedAssets = _.orderBy(filteredFiles, ['fileName'], ['asc']);
|
|
633
|
+
const skip = (pageNum - 1) * pageSize;
|
|
634
|
+
const totalPages = Math.ceil(filteredFiles.length / pageSize);
|
|
635
|
+
const pagesAssets = sortedAssets.slice(skip, skip + pageSize);
|
|
636
|
+
|
|
637
|
+
return {
|
|
638
|
+
assets: pagesAssets,
|
|
639
|
+
pageSize: pageSize,
|
|
640
|
+
pageNum: pageNum,
|
|
641
|
+
totalPages: totalPages
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async createAndLinkDocument({
|
|
646
|
+
srcType,
|
|
647
|
+
srcProjectId,
|
|
648
|
+
srcDocumentId,
|
|
649
|
+
fieldPath,
|
|
650
|
+
modelName,
|
|
651
|
+
object,
|
|
652
|
+
index,
|
|
653
|
+
locale,
|
|
654
|
+
user
|
|
655
|
+
}: {
|
|
656
|
+
srcType: string;
|
|
657
|
+
srcProjectId: string;
|
|
658
|
+
srcDocumentId: string;
|
|
659
|
+
fieldPath: (string | number)[];
|
|
660
|
+
modelName?: string;
|
|
661
|
+
object?: Record<string, any>;
|
|
662
|
+
index?: number;
|
|
663
|
+
locale?: string;
|
|
664
|
+
user?: ContentStoreTypes.User;
|
|
665
|
+
}): Promise<{ srcDocumentId: string }> {
|
|
666
|
+
this.logger.debug('createAndLinkDocument', { srcType, srcProjectId, srcDocumentId, fieldPath, modelName, index, locale });
|
|
667
|
+
|
|
668
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
669
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
670
|
+
|
|
671
|
+
// get the document that is being updated
|
|
672
|
+
const document = contentSourceData.documentMap[srcDocumentId];
|
|
673
|
+
const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
|
|
674
|
+
if (!document || !csiDocument) {
|
|
675
|
+
throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// get the document model
|
|
679
|
+
const documentModelName = document.srcModelName;
|
|
680
|
+
const modelMap = contentSourceData.modelMap;
|
|
681
|
+
const model = modelMap[documentModelName];
|
|
682
|
+
if (!model) {
|
|
683
|
+
throw new Error(`error updating document, could not find document model: '${documentModelName}'`);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// get the 'reference' model field in the updated document that will be used to link the new document
|
|
687
|
+
locale = locale ?? contentSourceData.defaultLocaleCode;
|
|
688
|
+
const modelField = getModelFieldForFieldAtPath(document, model, fieldPath, modelMap, locale);
|
|
689
|
+
if (!modelField) {
|
|
690
|
+
throw Error(`the "fieldPath" points to non existing model field: ${fieldPath.join('.')}`);
|
|
691
|
+
}
|
|
692
|
+
const fieldProps = modelField.type === 'list' ? modelField.items! : modelField;
|
|
693
|
+
if (fieldProps.type !== 'reference') {
|
|
694
|
+
throw Error(`error in "createAndLinkDocument", this operation can only be used on reference field: ${fieldPath.join('.')}`);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// get the model name for the new document
|
|
698
|
+
if (!modelName && fieldProps.models.length === 1) {
|
|
699
|
+
modelName = fieldProps.models[0];
|
|
700
|
+
}
|
|
701
|
+
if (!modelName) {
|
|
702
|
+
throw Error(`error in "createAndLinkDocument", missing "modelName": ${fieldPath.join('.')}`);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// create the new document
|
|
706
|
+
const result = await this.createDocument({
|
|
707
|
+
object: object,
|
|
708
|
+
srcProjectId: srcProjectId,
|
|
709
|
+
srcType: srcType,
|
|
710
|
+
modelName: modelName,
|
|
711
|
+
locale: locale,
|
|
712
|
+
user: user
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
// update the document by linking the field to the created document
|
|
716
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
717
|
+
const field = {
|
|
718
|
+
type: 'reference',
|
|
719
|
+
refType: 'document',
|
|
720
|
+
refId: result.srcDocumentId
|
|
721
|
+
} as const;
|
|
722
|
+
const updatedDocument = await contentSourceData.instance.updateDocument({
|
|
723
|
+
document: csiDocument,
|
|
724
|
+
modelMap: modelMap,
|
|
725
|
+
userContext: userContext,
|
|
726
|
+
operations: [
|
|
727
|
+
modelField.type === 'list'
|
|
728
|
+
? {
|
|
729
|
+
opType: 'insert',
|
|
730
|
+
fieldPath: fieldPath,
|
|
731
|
+
modelField: modelField,
|
|
732
|
+
locale: locale,
|
|
733
|
+
index: index,
|
|
734
|
+
item: field
|
|
735
|
+
}
|
|
736
|
+
: {
|
|
737
|
+
opType: 'set',
|
|
738
|
+
fieldPath: fieldPath,
|
|
739
|
+
modelField: modelField,
|
|
740
|
+
locale: locale,
|
|
741
|
+
field: field
|
|
742
|
+
}
|
|
743
|
+
]
|
|
744
|
+
});
|
|
745
|
+
return { srcDocumentId: updatedDocument.id };
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
async uploadAndLinkAsset({
|
|
749
|
+
srcType,
|
|
750
|
+
srcProjectId,
|
|
751
|
+
srcDocumentId,
|
|
752
|
+
fieldPath,
|
|
753
|
+
asset,
|
|
754
|
+
index,
|
|
755
|
+
locale,
|
|
756
|
+
user
|
|
757
|
+
}: {
|
|
758
|
+
srcType: string;
|
|
759
|
+
srcProjectId: string;
|
|
760
|
+
srcDocumentId: string;
|
|
761
|
+
fieldPath: (string | number)[];
|
|
762
|
+
asset: ContentStoreTypes.UploadAssetData;
|
|
763
|
+
index?: number;
|
|
764
|
+
locale?: string;
|
|
765
|
+
user?: ContentStoreTypes.User;
|
|
766
|
+
}): Promise<{ srcDocumentId: string }> {
|
|
767
|
+
this.logger.debug('uploadAndLinkAsset', { srcType, srcProjectId, srcDocumentId, fieldPath, index, locale });
|
|
768
|
+
|
|
769
|
+
// get the document that is being updated
|
|
770
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
771
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
772
|
+
const document = contentSourceData.documentMap[srcDocumentId];
|
|
773
|
+
const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
|
|
774
|
+
if (!document || !csiDocument) {
|
|
775
|
+
throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// get the document model
|
|
779
|
+
const documentModelName = document.srcModelName;
|
|
780
|
+
const modelMap = contentSourceData.modelMap;
|
|
781
|
+
const model = modelMap[documentModelName];
|
|
782
|
+
if (!model) {
|
|
783
|
+
throw new Error(`error updating document, could not find document model: '${documentModelName}'`);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// get the 'reference' model field in the updated document that will be used to link the new asset
|
|
787
|
+
locale = locale ?? contentSourceData.defaultLocaleCode;
|
|
788
|
+
const modelField = getModelFieldForFieldAtPath(document, model, fieldPath, modelMap, locale);
|
|
789
|
+
if (!modelField) {
|
|
790
|
+
throw Error(`the "fieldPath" points to non existing model field: ${fieldPath.join('.')}`);
|
|
791
|
+
}
|
|
792
|
+
const fieldProps = modelField.type === 'list' ? modelField.items! : modelField;
|
|
793
|
+
if (fieldProps.type !== 'reference' && fieldProps.type !== 'image') {
|
|
794
|
+
throw Error(`error in "uploadAndLinkAsset", this operation can only be used on reference and image fields: ${fieldPath.join('.')}`);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// upload the new asset
|
|
798
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
799
|
+
const result = await contentSourceData.instance.uploadAsset({
|
|
800
|
+
url: asset.url,
|
|
801
|
+
fileName: asset.metadata.name,
|
|
802
|
+
mimeType: asset.metadata.type,
|
|
803
|
+
locale: locale,
|
|
804
|
+
userContext: userContext
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
// update the document by linking the field to the created asset
|
|
808
|
+
const field = {
|
|
809
|
+
type: 'reference',
|
|
810
|
+
refType: 'asset',
|
|
811
|
+
refId: result.id
|
|
812
|
+
} as const;
|
|
813
|
+
const updatedDocument = await contentSourceData.instance.updateDocument({
|
|
814
|
+
document: csiDocument,
|
|
815
|
+
modelMap: modelMap,
|
|
816
|
+
userContext: userContext,
|
|
817
|
+
operations: [
|
|
818
|
+
modelField.type === 'list'
|
|
819
|
+
? {
|
|
820
|
+
opType: 'insert',
|
|
821
|
+
fieldPath: fieldPath,
|
|
822
|
+
modelField: modelField,
|
|
823
|
+
locale: locale,
|
|
824
|
+
index: index,
|
|
825
|
+
item: field
|
|
826
|
+
}
|
|
827
|
+
: {
|
|
828
|
+
opType: 'set',
|
|
829
|
+
fieldPath: fieldPath,
|
|
830
|
+
modelField: modelField,
|
|
831
|
+
locale: locale,
|
|
832
|
+
field: field
|
|
833
|
+
}
|
|
834
|
+
]
|
|
835
|
+
});
|
|
836
|
+
return { srcDocumentId: updatedDocument.id };
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
async createDocument({
|
|
840
|
+
srcType,
|
|
841
|
+
srcProjectId,
|
|
842
|
+
modelName,
|
|
843
|
+
object,
|
|
844
|
+
locale,
|
|
845
|
+
user
|
|
846
|
+
}: {
|
|
847
|
+
srcType: string;
|
|
848
|
+
srcProjectId: string;
|
|
849
|
+
modelName: string;
|
|
850
|
+
object?: Record<string, any>;
|
|
851
|
+
locale?: string;
|
|
852
|
+
user?: ContentStoreTypes.User;
|
|
853
|
+
}): Promise<{ srcDocumentId: string }> {
|
|
854
|
+
this.logger.debug('createDocument', { srcType, srcProjectId, modelName, locale });
|
|
855
|
+
|
|
856
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
857
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
858
|
+
const modelMap = contentSourceData.modelMap;
|
|
859
|
+
const model = modelMap[modelName];
|
|
860
|
+
if (!model) {
|
|
861
|
+
throw new Error(`no model with name '${modelName}' was found`);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
locale = locale ?? contentSourceData.defaultLocaleCode;
|
|
865
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
866
|
+
const result = await createDocumentRecursively({
|
|
867
|
+
object,
|
|
868
|
+
model,
|
|
869
|
+
modelMap,
|
|
870
|
+
locale,
|
|
871
|
+
userContext,
|
|
872
|
+
contentSourceInstance: contentSourceData.instance
|
|
873
|
+
});
|
|
874
|
+
this.logger.debug('created document', { srcType, srcProjectId, srcDocumentId: result.document.id, modelName });
|
|
875
|
+
|
|
876
|
+
// do not update cache in contentSourceData.documents and documentMap,
|
|
877
|
+
// instead wait for contentSource to call onContentChange(contentChangeEvent)
|
|
878
|
+
// and use data from contentChangeEvent to update the cache
|
|
879
|
+
// const newDocuments = [result.document, ...result.referencedDocuments];
|
|
880
|
+
// contentSourceData.documentMap = Object.assign(contentSourceData.documentMap, _.keyBy(newDocuments, 'srcObjectId'));
|
|
881
|
+
|
|
882
|
+
return { srcDocumentId: result.document.id };
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
async updateDocument({
|
|
886
|
+
srcType,
|
|
887
|
+
srcProjectId,
|
|
888
|
+
srcDocumentId,
|
|
889
|
+
updateOperations,
|
|
890
|
+
user
|
|
891
|
+
}: {
|
|
892
|
+
srcType: string;
|
|
893
|
+
srcProjectId: string;
|
|
894
|
+
srcDocumentId: string;
|
|
895
|
+
updateOperations: ContentStoreTypes.UpdateOperation[];
|
|
896
|
+
user?: ContentStoreTypes.User;
|
|
897
|
+
}): Promise<{ srcDocumentId: string }> {
|
|
898
|
+
this.logger.debug('updateDocument');
|
|
899
|
+
|
|
900
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
901
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
902
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
903
|
+
const document = contentSourceData.documentMap[srcDocumentId];
|
|
904
|
+
const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
|
|
905
|
+
if (!document || !csiDocument) {
|
|
906
|
+
throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
const modelMap = contentSourceData.modelMap;
|
|
910
|
+
const documentModelName = document.srcModelName;
|
|
911
|
+
const model = modelMap[documentModelName];
|
|
912
|
+
if (!model) {
|
|
913
|
+
throw new Error(`error updating document, could not find document model: '${documentModelName}'`);
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
const operations = await mapPromise(
|
|
917
|
+
updateOperations,
|
|
918
|
+
async (updateOperation): Promise<CSITypes.UpdateOperation> => {
|
|
919
|
+
const locale = updateOperation.locale ?? contentSourceData.defaultLocaleCode;
|
|
920
|
+
const modelField = getModelFieldForFieldAtPath(document, model, updateOperation.fieldPath, modelMap, locale);
|
|
921
|
+
switch (updateOperation.opType) {
|
|
922
|
+
case 'set':
|
|
923
|
+
const field = await convertOperationField({
|
|
924
|
+
operationField: updateOperation.field,
|
|
925
|
+
fieldPath: updateOperation.fieldPath,
|
|
926
|
+
locale: updateOperation.locale,
|
|
927
|
+
modelField,
|
|
928
|
+
modelMap,
|
|
929
|
+
userContext,
|
|
930
|
+
contentSourceInstance: contentSourceData.instance
|
|
931
|
+
});
|
|
932
|
+
return {
|
|
933
|
+
...updateOperation,
|
|
934
|
+
modelField,
|
|
935
|
+
field
|
|
936
|
+
};
|
|
937
|
+
case 'unset':
|
|
938
|
+
return { ...updateOperation, modelField };
|
|
939
|
+
case 'insert':
|
|
940
|
+
const item = await convertOperationField({
|
|
941
|
+
operationField: updateOperation.item,
|
|
942
|
+
fieldPath: updateOperation.fieldPath,
|
|
943
|
+
locale: updateOperation.locale,
|
|
944
|
+
modelField,
|
|
945
|
+
modelMap,
|
|
946
|
+
userContext,
|
|
947
|
+
contentSourceInstance: contentSourceData.instance
|
|
948
|
+
});
|
|
949
|
+
return {
|
|
950
|
+
...updateOperation,
|
|
951
|
+
modelField,
|
|
952
|
+
item
|
|
953
|
+
};
|
|
954
|
+
case 'remove':
|
|
955
|
+
return { ...updateOperation, modelField };
|
|
956
|
+
case 'reorder':
|
|
957
|
+
return { ...updateOperation, modelField };
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
);
|
|
961
|
+
|
|
962
|
+
const updatedDocumentResult = await contentSourceData.instance.updateDocument({
|
|
963
|
+
document: csiDocument,
|
|
964
|
+
modelMap,
|
|
965
|
+
userContext,
|
|
966
|
+
operations
|
|
967
|
+
});
|
|
968
|
+
|
|
969
|
+
// do not update cache in contentSourceData.documents and documentMap,
|
|
970
|
+
// instead wait for contentSource to call onContentChange(contentChangeEvent)
|
|
971
|
+
// and use data from contentChangeEvent to update the cache
|
|
972
|
+
// contentSourceData.documentMap = Object.assign(contentSourceData.documentMap, { [document.srcObjectId]: document });
|
|
973
|
+
|
|
974
|
+
return { srcDocumentId: updatedDocumentResult.id };
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
async duplicateDocument({
|
|
978
|
+
srcType,
|
|
979
|
+
srcProjectId,
|
|
980
|
+
srcDocumentId,
|
|
981
|
+
object,
|
|
982
|
+
user
|
|
983
|
+
}: {
|
|
984
|
+
srcType: string;
|
|
985
|
+
srcProjectId: string;
|
|
986
|
+
srcDocumentId: string;
|
|
987
|
+
object?: Record<string, any>;
|
|
988
|
+
user?: ContentStoreTypes.User;
|
|
989
|
+
}): Promise<{ srcDocumentId: string }> {
|
|
990
|
+
this.logger.debug('duplicateDocument');
|
|
991
|
+
|
|
992
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
993
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
994
|
+
const document = contentSourceData.documentMap[srcDocumentId];
|
|
995
|
+
if (!document) {
|
|
996
|
+
throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
|
|
997
|
+
}
|
|
998
|
+
const modelMap = contentSourceData.modelMap;
|
|
999
|
+
const model = modelMap[document.srcModelName];
|
|
1000
|
+
if (!model) {
|
|
1001
|
+
throw new Error(`no model with name '${document.srcModelName}' was found`);
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
1005
|
+
// TODO: handle duplicatable and non duplicatable models
|
|
1006
|
+
// TODO: handle fields from the provided object
|
|
1007
|
+
const documentResult = await contentSourceData.instance.createDocument({
|
|
1008
|
+
documentFields: mapStoreFieldsToSourceFields({
|
|
1009
|
+
documentFields: document.fields,
|
|
1010
|
+
modelFields: model.fields!,
|
|
1011
|
+
modelMap: contentSourceData.modelMap
|
|
1012
|
+
}),
|
|
1013
|
+
model,
|
|
1014
|
+
modelMap,
|
|
1015
|
+
locale: contentSourceData.defaultLocaleCode,
|
|
1016
|
+
userContext
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
return { srcDocumentId: documentResult.id };
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
async uploadAssets({
|
|
1023
|
+
srcType,
|
|
1024
|
+
srcProjectId,
|
|
1025
|
+
assets,
|
|
1026
|
+
locale,
|
|
1027
|
+
user
|
|
1028
|
+
}: {
|
|
1029
|
+
srcType: string;
|
|
1030
|
+
srcProjectId: string;
|
|
1031
|
+
assets: ContentStoreTypes.UploadAssetData[];
|
|
1032
|
+
locale?: string;
|
|
1033
|
+
user?: ContentStoreTypes.User;
|
|
1034
|
+
}): Promise<ContentStoreTypes.APIAsset[]> {
|
|
1035
|
+
this.logger.debug('uploadAssets');
|
|
1036
|
+
|
|
1037
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
1038
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
1039
|
+
const sourceAssets: CSITypes.Asset[] = [];
|
|
1040
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
1041
|
+
|
|
1042
|
+
locale = locale ?? contentSourceData.defaultLocaleCode;
|
|
1043
|
+
|
|
1044
|
+
for (const asset of assets) {
|
|
1045
|
+
let base64 = undefined;
|
|
1046
|
+
if (asset.data) {
|
|
1047
|
+
const matchResult = asset.data.match(/;base64,([\s\S]+)$/);
|
|
1048
|
+
if (matchResult) {
|
|
1049
|
+
base64 = matchResult[1];
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
const sourceAsset = await contentSourceData.instance.uploadAsset({
|
|
1053
|
+
url: asset.url,
|
|
1054
|
+
base64: base64,
|
|
1055
|
+
fileName: asset.metadata.name,
|
|
1056
|
+
mimeType: asset.metadata.type,
|
|
1057
|
+
locale: locale,
|
|
1058
|
+
userContext: userContext
|
|
1059
|
+
});
|
|
1060
|
+
sourceAssets.push(sourceAsset);
|
|
1061
|
+
}
|
|
1062
|
+
const storeAssets = mapCSIAssetsToStoreAssets({
|
|
1063
|
+
csiAssets: sourceAssets,
|
|
1064
|
+
contentSourceInstance: contentSourceData.instance,
|
|
1065
|
+
defaultLocaleCode: contentSourceData.defaultLocaleCode
|
|
1066
|
+
});
|
|
1067
|
+
return mapStoreAssetsToAPIAssets(storeAssets, locale);
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
async deleteDocument({
|
|
1071
|
+
srcType,
|
|
1072
|
+
srcProjectId,
|
|
1073
|
+
srcDocumentId,
|
|
1074
|
+
user
|
|
1075
|
+
}: {
|
|
1076
|
+
srcType: string;
|
|
1077
|
+
srcProjectId: string;
|
|
1078
|
+
srcDocumentId: string;
|
|
1079
|
+
user?: ContentStoreTypes.User;
|
|
1080
|
+
}) {
|
|
1081
|
+
this.logger.debug('deleteDocument');
|
|
1082
|
+
|
|
1083
|
+
const userContext = getUserContextForSrcType(srcType, user);
|
|
1084
|
+
const contentSourceId = getContentSourceId(srcType, srcProjectId);
|
|
1085
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
1086
|
+
const csiDocument = contentSourceData.csiDocumentMap[srcDocumentId];
|
|
1087
|
+
if (!csiDocument) {
|
|
1088
|
+
throw new Error(`no document with id '${srcDocumentId}' was found in ${contentSourceData.id}`);
|
|
1089
|
+
}
|
|
1090
|
+
await contentSourceData.instance.deleteDocument({ document: csiDocument, userContext });
|
|
1091
|
+
|
|
1092
|
+
// do not update cache in contentSourceData.documents and documentMap,
|
|
1093
|
+
// instead wait for contentSource to call onContentChange(contentChangeEvent)
|
|
1094
|
+
// and use data from contentChangeEvent to update the cache
|
|
1095
|
+
// delete contentSourceData.documentMap[srcDocumentId];
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
async validateDocuments({
|
|
1099
|
+
objects,
|
|
1100
|
+
locale,
|
|
1101
|
+
user
|
|
1102
|
+
}: {
|
|
1103
|
+
objects: { srcType: string; srcProjectId: string; srcObjectId: string }[];
|
|
1104
|
+
locale?: string;
|
|
1105
|
+
user?: ContentStoreTypes.User;
|
|
1106
|
+
}): Promise<{ errors: ContentStoreTypes.ValidationError[] }> {
|
|
1107
|
+
this.logger.debug('validateDocuments');
|
|
1108
|
+
|
|
1109
|
+
const objectsBySourceId = _.groupBy(objects, (object) => getContentSourceId(object.srcType, object.srcProjectId));
|
|
1110
|
+
let errors: ContentStoreTypes.ValidationError[] = [];
|
|
1111
|
+
for (const [contentSourceId, contentSourceObjects] of Object.entries(objectsBySourceId)) {
|
|
1112
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
1113
|
+
locale = locale ?? contentSourceData.defaultLocaleCode;
|
|
1114
|
+
const { documents, assets } = getCSIDocumentsAndAssetsFromContentSourceDataByIds(contentSourceData, contentSourceObjects);
|
|
1115
|
+
const userContext = getUserContextForSrcType(contentSourceData.type, user);
|
|
1116
|
+
const validationResult = await contentSourceData.instance.validateDocuments({ documents, assets, locale, userContext });
|
|
1117
|
+
errors = errors.concat(
|
|
1118
|
+
validationResult.errors.map((validationError) => ({
|
|
1119
|
+
message: validationError.message,
|
|
1120
|
+
srcType: contentSourceData.type,
|
|
1121
|
+
srcProjectId: contentSourceData.projectId,
|
|
1122
|
+
srcObjectType: validationError.objectType,
|
|
1123
|
+
srcObjectId: validationError.objectId,
|
|
1124
|
+
fieldPath: validationError.fieldPath,
|
|
1125
|
+
isUniqueValidation: validationError.isUniqueValidation
|
|
1126
|
+
}))
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
return { errors };
|
|
1131
|
+
|
|
1132
|
+
/* validate for multiple sources
|
|
1133
|
+
const objectsBySourceId = _.groupBy(objects, (document) => getContentSourceId(document.srcType, document.srcProjectId));
|
|
1134
|
+
const contentSourceIds = Object.keys(objectsBySourceId);
|
|
1135
|
+
return reducePromise(
|
|
1136
|
+
contentSourceIds,
|
|
1137
|
+
async (result: ContentStoreTypes.ValidationError[], contentSourceId) => {
|
|
1138
|
+
const documents = documentsBySourceId[contentSourceId]!;
|
|
1139
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
1140
|
+
const validationErrors = await contentSourceData.instance.validateDocuments({ documentIds: documents.map((document) => document.srcObjectId) });
|
|
1141
|
+
return result.concat(validationErrors);
|
|
1142
|
+
},
|
|
1143
|
+
[]
|
|
1144
|
+
);
|
|
1145
|
+
*/
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
async publishDocuments({ objects, user }: { objects: { srcType: string; srcProjectId: string; srcObjectId: string }[]; user?: ContentStoreTypes.User }) {
|
|
1149
|
+
this.logger.debug('publishDocuments');
|
|
1150
|
+
|
|
1151
|
+
const objectsBySourceId = _.groupBy(objects, (object) => getContentSourceId(object.srcType, object.srcProjectId));
|
|
1152
|
+
for (const [contentSourceId, contentSourceObjects] of Object.entries(objectsBySourceId)) {
|
|
1153
|
+
const contentSourceData = this.getContentSourceDataByIdOrThrow(contentSourceId);
|
|
1154
|
+
const userContext = getUserContextForSrcType(contentSourceData.type, user);
|
|
1155
|
+
const { documents, assets } = getCSIDocumentsAndAssetsFromContentSourceDataByIds(contentSourceData, contentSourceObjects);
|
|
1156
|
+
await contentSourceData.instance.publishDocuments({ documents, assets, userContext });
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
private getContentSourceDataByIdOrThrow(contentSourceId: string): ContentSourceData {
|
|
1161
|
+
const contentSourceData = this.contentSourceDataById[contentSourceId];
|
|
1162
|
+
if (!contentSourceData) {
|
|
1163
|
+
throw new Error(`no content source for id '${contentSourceId}' was found`);
|
|
1164
|
+
}
|
|
1165
|
+
return contentSourceData;
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
export function getContentSourceId(contentSourceType: string, srcProjectId: string) {
|
|
1170
|
+
return contentSourceType + ':' + srcProjectId;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
function getUserContextForSrcType(srcType: string, user?: ContentStoreTypes.User): unknown {
|
|
1174
|
+
return user?.connections?.find((connection) => connection.type === srcType);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
function mapCSIAssetsToStoreAssets({
|
|
1178
|
+
csiAssets,
|
|
1179
|
+
contentSourceInstance,
|
|
1180
|
+
defaultLocaleCode
|
|
1181
|
+
}: {
|
|
1182
|
+
csiAssets: CSITypes.Asset[];
|
|
1183
|
+
contentSourceInstance: CSITypes.ContentSourceInterface;
|
|
1184
|
+
defaultLocaleCode?: string;
|
|
1185
|
+
}): ContentStoreTypes.Asset[] {
|
|
1186
|
+
const extra = {
|
|
1187
|
+
srcType: contentSourceInstance.getContentSourceType(),
|
|
1188
|
+
srcProjectId: contentSourceInstance.getProjectId(),
|
|
1189
|
+
srcProjectUrl: contentSourceInstance.getProjectManageUrl(),
|
|
1190
|
+
srcEnvironment: contentSourceInstance.getProjectEnvironment()
|
|
1191
|
+
};
|
|
1192
|
+
return csiAssets.map((csiAsset) => sourceAssetToStoreAsset({ csiAsset, defaultLocaleCode, extra }));
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function sourceAssetToStoreAsset({
|
|
1196
|
+
csiAsset,
|
|
1197
|
+
defaultLocaleCode,
|
|
1198
|
+
extra
|
|
1199
|
+
}: {
|
|
1200
|
+
csiAsset: CSITypes.Asset;
|
|
1201
|
+
defaultLocaleCode?: string;
|
|
1202
|
+
extra: { srcType: string; srcProjectId: string; srcProjectUrl: string; srcEnvironment: string };
|
|
1203
|
+
}): ContentStoreTypes.Asset {
|
|
1204
|
+
return {
|
|
1205
|
+
type: 'asset',
|
|
1206
|
+
...extra,
|
|
1207
|
+
srcObjectId: csiAsset.id,
|
|
1208
|
+
srcObjectUrl: csiAsset.manageUrl,
|
|
1209
|
+
srcObjectLabel: getObjectLabel(csiAsset.fields, IMAGE_MODEL, defaultLocaleCode),
|
|
1210
|
+
srcModelName: IMAGE_MODEL.name,
|
|
1211
|
+
srcModelLabel: IMAGE_MODEL.label!,
|
|
1212
|
+
isChanged: csiAsset.status === 'added' || csiAsset.status === 'modified',
|
|
1213
|
+
status: csiAsset.status,
|
|
1214
|
+
createdAt: csiAsset.createdAt,
|
|
1215
|
+
createdBy: csiAsset.createdBy,
|
|
1216
|
+
updatedAt: csiAsset.updatedAt,
|
|
1217
|
+
updatedBy: csiAsset.updatedBy,
|
|
1218
|
+
fields: {
|
|
1219
|
+
title: {
|
|
1220
|
+
label: 'Title',
|
|
1221
|
+
...csiAsset.fields.title
|
|
1222
|
+
},
|
|
1223
|
+
file: {
|
|
1224
|
+
label: 'File',
|
|
1225
|
+
...csiAsset.fields.file
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
function mapCSIDocumentsToStoreDocuments({
|
|
1232
|
+
csiDocuments,
|
|
1233
|
+
contentSourceInstance,
|
|
1234
|
+
modelMap,
|
|
1235
|
+
defaultLocaleCode
|
|
1236
|
+
}: {
|
|
1237
|
+
csiDocuments: CSITypes.Document[];
|
|
1238
|
+
contentSourceInstance: CSITypes.ContentSourceInterface;
|
|
1239
|
+
modelMap: Record<string, Model>;
|
|
1240
|
+
defaultLocaleCode?: string;
|
|
1241
|
+
}): ContentStoreTypes.Document[] {
|
|
1242
|
+
const extra = {
|
|
1243
|
+
srcType: contentSourceInstance.getContentSourceType(),
|
|
1244
|
+
srcProjectId: contentSourceInstance.getProjectId(),
|
|
1245
|
+
srcProjectUrl: contentSourceInstance.getProjectManageUrl(),
|
|
1246
|
+
srcEnvironment: contentSourceInstance.getProjectEnvironment()
|
|
1247
|
+
};
|
|
1248
|
+
return csiDocuments.map((csiDocument) =>
|
|
1249
|
+
mapCSIDocumentToStoreDocument({ csiDocument, model: modelMap[csiDocument.modelName]!, modelMap, defaultLocaleCode, extra })
|
|
1250
|
+
);
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
function mapCSIDocumentToStoreDocument({
|
|
1254
|
+
csiDocument,
|
|
1255
|
+
model,
|
|
1256
|
+
modelMap,
|
|
1257
|
+
defaultLocaleCode,
|
|
1258
|
+
extra
|
|
1259
|
+
}: {
|
|
1260
|
+
csiDocument: CSITypes.Document;
|
|
1261
|
+
model: Model;
|
|
1262
|
+
modelMap: Record<string, Model>;
|
|
1263
|
+
defaultLocaleCode?: string;
|
|
1264
|
+
extra: { srcType: string; srcProjectId: string; srcProjectUrl: string; srcEnvironment: string };
|
|
1265
|
+
}): ContentStoreTypes.Document {
|
|
1266
|
+
return {
|
|
1267
|
+
type: 'document',
|
|
1268
|
+
...extra,
|
|
1269
|
+
srcObjectId: csiDocument.id,
|
|
1270
|
+
srcObjectUrl: csiDocument.manageUrl,
|
|
1271
|
+
srcObjectLabel: getObjectLabel(csiDocument.fields, model, defaultLocaleCode),
|
|
1272
|
+
srcModelLabel: model.label ?? _.startCase(csiDocument.modelName),
|
|
1273
|
+
srcModelName: csiDocument.modelName,
|
|
1274
|
+
isChanged: csiDocument.status === 'added' || csiDocument.status === 'modified',
|
|
1275
|
+
status: csiDocument.status,
|
|
1276
|
+
createdAt: csiDocument.createdAt,
|
|
1277
|
+
createdBy: csiDocument.createdBy,
|
|
1278
|
+
updatedAt: csiDocument.updatedAt,
|
|
1279
|
+
updatedBy: csiDocument.updatedBy,
|
|
1280
|
+
fields: mapCSIFieldsToStoreFields({
|
|
1281
|
+
csiDocumentFields: csiDocument.fields,
|
|
1282
|
+
modelFields: model.fields ?? [],
|
|
1283
|
+
context: {
|
|
1284
|
+
modelMap,
|
|
1285
|
+
defaultLocaleCode
|
|
1286
|
+
}
|
|
1287
|
+
})
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
type MapContext = {
|
|
1292
|
+
modelMap: Record<string, Model>;
|
|
1293
|
+
defaultLocaleCode?: string;
|
|
1294
|
+
};
|
|
1295
|
+
|
|
1296
|
+
function mapCSIFieldsToStoreFields({
|
|
1297
|
+
csiDocumentFields,
|
|
1298
|
+
modelFields,
|
|
1299
|
+
context
|
|
1300
|
+
}: {
|
|
1301
|
+
csiDocumentFields: Record<string, CSITypes.DocumentField>;
|
|
1302
|
+
modelFields: Field[];
|
|
1303
|
+
context: MapContext;
|
|
1304
|
+
}): Record<string, ContentStoreTypes.DocumentField> {
|
|
1305
|
+
return modelFields.reduce((result: Record<string, ContentStoreTypes.DocumentField>, modelField) => {
|
|
1306
|
+
const csiDocumentField = csiDocumentFields[modelField.name];
|
|
1307
|
+
const docField = mapCSIFieldToStoreField({
|
|
1308
|
+
csiDocumentField,
|
|
1309
|
+
modelField,
|
|
1310
|
+
context
|
|
1311
|
+
});
|
|
1312
|
+
docField.label = modelField.label;
|
|
1313
|
+
result[modelField.name] = docField;
|
|
1314
|
+
return result;
|
|
1315
|
+
}, {});
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
function mapCSIFieldToStoreField({
|
|
1319
|
+
csiDocumentField,
|
|
1320
|
+
modelField,
|
|
1321
|
+
context
|
|
1322
|
+
}: {
|
|
1323
|
+
csiDocumentField: CSITypes.DocumentField | undefined;
|
|
1324
|
+
modelField: FieldSpecificProps;
|
|
1325
|
+
context: MapContext;
|
|
1326
|
+
}): ContentStoreTypes.DocumentField {
|
|
1327
|
+
if (!csiDocumentField) {
|
|
1328
|
+
const isUnset = ['object', 'model', 'reference', 'richText', 'markdown', 'image', 'file', 'json'].includes(modelField.type);
|
|
1329
|
+
return {
|
|
1330
|
+
type: modelField.type,
|
|
1331
|
+
...(isUnset ? { isUnset } : null),
|
|
1332
|
+
...(modelField.type === 'list' ? { items: [] } : null)
|
|
1333
|
+
} as ContentStoreTypes.DocumentField;
|
|
1334
|
+
}
|
|
1335
|
+
// TODO: check if need to add "options" to "enum" and subtype/min/max to "number"
|
|
1336
|
+
switch (modelField.type) {
|
|
1337
|
+
case 'object':
|
|
1338
|
+
return mapObjectField(csiDocumentField as CSITypes.DocumentObjectField, modelField, context);
|
|
1339
|
+
case 'model':
|
|
1340
|
+
return mapModelField(csiDocumentField as CSITypes.DocumentModelField, modelField, context);
|
|
1341
|
+
case 'list':
|
|
1342
|
+
return mapListField(csiDocumentField as CSITypes.DocumentListField, modelField, context);
|
|
1343
|
+
case 'richText':
|
|
1344
|
+
return mapRichTextField(csiDocumentField as CSITypes.DocumentRichTextField);
|
|
1345
|
+
case 'markdown':
|
|
1346
|
+
return mapMarkdownField(csiDocumentField as CSITypes.DocumentValueField);
|
|
1347
|
+
default:
|
|
1348
|
+
return csiDocumentField as ContentStoreTypes.DocumentField;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
function mapObjectField(
|
|
1353
|
+
csiDocumentField: CSITypes.DocumentObjectField,
|
|
1354
|
+
modelField: FieldObjectProps,
|
|
1355
|
+
context: MapContext
|
|
1356
|
+
): ContentStoreTypes.DocumentObjectField {
|
|
1357
|
+
if (!isLocalizedField(csiDocumentField)) {
|
|
1358
|
+
return {
|
|
1359
|
+
type: csiDocumentField.type,
|
|
1360
|
+
srcObjectLabel: getObjectLabel(csiDocumentField.fields ?? {}, modelField ?? [], context.defaultLocaleCode),
|
|
1361
|
+
fields: mapCSIFieldsToStoreFields({
|
|
1362
|
+
csiDocumentFields: csiDocumentField.fields ?? {},
|
|
1363
|
+
modelFields: modelField.fields ?? [],
|
|
1364
|
+
context
|
|
1365
|
+
})
|
|
1366
|
+
};
|
|
1367
|
+
}
|
|
1368
|
+
return {
|
|
1369
|
+
type: csiDocumentField.type,
|
|
1370
|
+
localized: true,
|
|
1371
|
+
locales: _.mapValues(csiDocumentField.locales, (locale) => {
|
|
1372
|
+
return {
|
|
1373
|
+
locale: locale.locale,
|
|
1374
|
+
srcObjectLabel: getObjectLabel(locale.fields ?? {}, modelField, locale.locale),
|
|
1375
|
+
fields: mapCSIFieldsToStoreFields({
|
|
1376
|
+
csiDocumentFields: locale.fields ?? {},
|
|
1377
|
+
modelFields: modelField.fields ?? [],
|
|
1378
|
+
context
|
|
1379
|
+
})
|
|
1380
|
+
};
|
|
1381
|
+
})
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
function mapModelField(csiDocumentField: CSITypes.DocumentModelField, modelField: FieldModelProps, context: MapContext): ContentStoreTypes.DocumentModelField {
|
|
1386
|
+
if (!isLocalizedField(csiDocumentField)) {
|
|
1387
|
+
const model = context.modelMap[csiDocumentField.modelName]!;
|
|
1388
|
+
return {
|
|
1389
|
+
type: csiDocumentField.type,
|
|
1390
|
+
srcObjectLabel: getObjectLabel(csiDocumentField.fields ?? {}, model, context.defaultLocaleCode),
|
|
1391
|
+
srcModelName: csiDocumentField.modelName,
|
|
1392
|
+
srcModelLabel: model.label ?? _.startCase(model.name),
|
|
1393
|
+
fields: mapCSIFieldsToStoreFields({
|
|
1394
|
+
csiDocumentFields: csiDocumentField.fields ?? {},
|
|
1395
|
+
modelFields: model.fields ?? [],
|
|
1396
|
+
context
|
|
1397
|
+
})
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
return {
|
|
1401
|
+
type: csiDocumentField.type,
|
|
1402
|
+
localized: true,
|
|
1403
|
+
locales: _.mapValues(csiDocumentField.locales, (locale) => {
|
|
1404
|
+
const model = context.modelMap[locale.modelName]!;
|
|
1405
|
+
return {
|
|
1406
|
+
locale: locale.locale,
|
|
1407
|
+
srcObjectLabel: getObjectLabel(locale.fields ?? {}, model, locale.locale),
|
|
1408
|
+
srcModelName: locale.modelName,
|
|
1409
|
+
srcModelLabel: model.label ?? _.startCase(model.name),
|
|
1410
|
+
fields: mapCSIFieldsToStoreFields({
|
|
1411
|
+
csiDocumentFields: locale.fields ?? {},
|
|
1412
|
+
modelFields: model.fields ?? [],
|
|
1413
|
+
context
|
|
1414
|
+
})
|
|
1415
|
+
};
|
|
1416
|
+
})
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
function mapListField(csiDocumentField: CSITypes.DocumentListField, modelField: FieldListProps, context: MapContext): ContentStoreTypes.DocumentListField {
|
|
1421
|
+
if (!isLocalizedField(csiDocumentField)) {
|
|
1422
|
+
return {
|
|
1423
|
+
type: csiDocumentField.type,
|
|
1424
|
+
items: csiDocumentField.items.map((item) =>
|
|
1425
|
+
mapCSIFieldToStoreField({
|
|
1426
|
+
csiDocumentField: item,
|
|
1427
|
+
modelField: modelField.items ?? { type: 'string' },
|
|
1428
|
+
context
|
|
1429
|
+
})
|
|
1430
|
+
)
|
|
1431
|
+
};
|
|
1432
|
+
}
|
|
1433
|
+
return {
|
|
1434
|
+
type: csiDocumentField.type,
|
|
1435
|
+
localized: true,
|
|
1436
|
+
locales: _.mapValues(csiDocumentField.locales, (locale) => {
|
|
1437
|
+
return {
|
|
1438
|
+
locale: locale.locale,
|
|
1439
|
+
items: (locale.items ?? []).map((item) =>
|
|
1440
|
+
mapCSIFieldToStoreField({
|
|
1441
|
+
csiDocumentField: item,
|
|
1442
|
+
modelField: modelField.items ?? { type: 'string' },
|
|
1443
|
+
context
|
|
1444
|
+
})
|
|
1445
|
+
)
|
|
1446
|
+
};
|
|
1447
|
+
})
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
function mapRichTextField(csiDocumentField: CSITypes.DocumentRichTextField): ContentStoreTypes.DocumentRichTextField {
|
|
1452
|
+
if (!isLocalizedField(csiDocumentField)) {
|
|
1453
|
+
return {
|
|
1454
|
+
...csiDocumentField,
|
|
1455
|
+
multiElement: true
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1458
|
+
return {
|
|
1459
|
+
type: csiDocumentField.type,
|
|
1460
|
+
localized: true,
|
|
1461
|
+
locales: _.mapValues(csiDocumentField.locales, (locale) => {
|
|
1462
|
+
return {
|
|
1463
|
+
...locale,
|
|
1464
|
+
multiElement: true
|
|
1465
|
+
};
|
|
1466
|
+
})
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
function mapMarkdownField(csiDocumentField: CSITypes.DocumentValueField): ContentStoreTypes.DocumentMarkdownField {
|
|
1471
|
+
if (!isLocalizedField(csiDocumentField)) {
|
|
1472
|
+
return {
|
|
1473
|
+
type: 'markdown',
|
|
1474
|
+
value: csiDocumentField.value,
|
|
1475
|
+
multiElement: true
|
|
1476
|
+
};
|
|
1477
|
+
}
|
|
1478
|
+
return {
|
|
1479
|
+
type: 'markdown',
|
|
1480
|
+
localized: true,
|
|
1481
|
+
locales: _.mapValues(csiDocumentField.locales, (locale) => {
|
|
1482
|
+
return {
|
|
1483
|
+
...locale,
|
|
1484
|
+
multiElement: true
|
|
1485
|
+
};
|
|
1486
|
+
})
|
|
1487
|
+
};
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
function mapStoreFieldsToSourceFields({
|
|
1491
|
+
documentFields,
|
|
1492
|
+
modelFields,
|
|
1493
|
+
modelMap
|
|
1494
|
+
}: {
|
|
1495
|
+
documentFields: Record<string, ContentStoreTypes.DocumentField>;
|
|
1496
|
+
modelFields: Field[];
|
|
1497
|
+
modelMap: Record<string, Model>;
|
|
1498
|
+
}): Record<string, CSITypes.DocumentField> {
|
|
1499
|
+
// TODO: implement
|
|
1500
|
+
throw new Error(`duplicateDocument not implemented yet`);
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
function getContentSourceIdForContentSource(contentSource: CSITypes.ContentSourceInterface): string {
|
|
1504
|
+
return getContentSourceId(contentSource.getContentSourceType(), contentSource.getProjectId());
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
function extractTokensFromString(input: string): string[] {
|
|
1508
|
+
return input.match(/(?<={)[^}]+(?=})/g) || [];
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
function sanitizeSlug(slug: string) {
|
|
1512
|
+
return slug
|
|
1513
|
+
.split('/')
|
|
1514
|
+
.map((part) => slugify(part, { lower: true }))
|
|
1515
|
+
.join('/');
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
function getObjectLabel(
|
|
1519
|
+
documentFields: Record<string, CSITypes.DocumentField | CSITypes.AssetFileField>,
|
|
1520
|
+
modelOrObjectField: Model | FieldObjectProps,
|
|
1521
|
+
locale?: string
|
|
1522
|
+
): string {
|
|
1523
|
+
const labelField = modelOrObjectField.labelField;
|
|
1524
|
+
let label = null;
|
|
1525
|
+
if (labelField) {
|
|
1526
|
+
const field = _.get(documentFields, labelField, null);
|
|
1527
|
+
if (field && ['string', 'url', 'slug', 'text', 'markdown', 'number', 'enum', 'date', 'datetime', 'color', 'image', 'file'].includes(field.type)) {
|
|
1528
|
+
if (isLocalizedField(field) && locale) {
|
|
1529
|
+
label = _.get(field, ['locales', locale, 'value'], null);
|
|
1530
|
+
} else if (!isLocalizedField(field)) {
|
|
1531
|
+
label = _.get(field, 'value', null);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
if (!label) {
|
|
1536
|
+
label = _.get(modelOrObjectField, 'label');
|
|
1537
|
+
}
|
|
1538
|
+
if (!label && _.has(modelOrObjectField, 'name')) {
|
|
1539
|
+
label = _.startCase(_.get(modelOrObjectField, 'name'));
|
|
1540
|
+
}
|
|
1541
|
+
return label;
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
function mapDocumentsToLocalizedApiObjects(documents: ContentStoreTypes.Document[], locale?: string): ContentStoreTypes.APIDocumentObject[] {
|
|
1545
|
+
return documents.map((document) => documentToLocalizedApiObject(document, locale));
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
function documentToLocalizedApiObject(document: ContentStoreTypes.Document, locale?: string): ContentStoreTypes.APIDocumentObject {
|
|
1549
|
+
const { type, fields, ...rest } = document;
|
|
1550
|
+
return {
|
|
1551
|
+
type: 'object',
|
|
1552
|
+
...rest,
|
|
1553
|
+
fields: toLocalizedAPIFields(fields, locale)
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
function toLocalizedAPIFields(docFields: Record<string, ContentStoreTypes.DocumentField>, locale?: string): Record<string, ContentStoreTypes.DocumentFieldAPI> {
|
|
1558
|
+
return _.mapValues(docFields, (docField) => toLocalizedAPIField(docField, locale));
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
function toLocalizedAPIField(docField: ContentStoreTypes.DocumentField, locale?: string, isListItem = false): ContentStoreTypes.DocumentFieldAPI {
|
|
1562
|
+
const hasUnsetFlag = ['object', 'model', 'reference', 'richText', 'markdown', 'image', 'file', 'json'].includes(docField.type);
|
|
1563
|
+
let docFieldLocalized: ContentStoreTypes.DocumentFieldNonLocalized;
|
|
1564
|
+
let unset = false;
|
|
1565
|
+
if (docField.localized) {
|
|
1566
|
+
const { locales, localized, ...base } = docField;
|
|
1567
|
+
const localeProps = locale ? locales[locale] : undefined;
|
|
1568
|
+
docFieldLocalized = {
|
|
1569
|
+
...base,
|
|
1570
|
+
...localeProps,
|
|
1571
|
+
...(hasUnsetFlag && !localeProps ? { isUnset: true } : null)
|
|
1572
|
+
} as ContentStoreTypes.DocumentFieldNonLocalized;
|
|
1573
|
+
} else {
|
|
1574
|
+
docFieldLocalized = docField;
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
locale = locale ?? docFieldLocalized.locale;
|
|
1578
|
+
const commonProps = isListItem
|
|
1579
|
+
? null
|
|
1580
|
+
: {
|
|
1581
|
+
localized: !!docField.localized,
|
|
1582
|
+
...(locale ? { locale } : null)
|
|
1583
|
+
};
|
|
1584
|
+
|
|
1585
|
+
if (docFieldLocalized.type === 'object' || docFieldLocalized.type === 'model') {
|
|
1586
|
+
return {
|
|
1587
|
+
...docFieldLocalized,
|
|
1588
|
+
...commonProps,
|
|
1589
|
+
...(docFieldLocalized.isUnset
|
|
1590
|
+
? null
|
|
1591
|
+
: {
|
|
1592
|
+
fields: toLocalizedAPIFields(docFieldLocalized.fields, locale)
|
|
1593
|
+
})
|
|
1594
|
+
} as ContentStoreTypes.DocumentObjectFieldAPI | ContentStoreTypes.DocumentModelFieldAPI;
|
|
1595
|
+
} else if (docFieldLocalized.type === 'reference') {
|
|
1596
|
+
const { type, refType, ...rest } = docFieldLocalized;
|
|
1597
|
+
// if reference field isUnset === true, it behaves like a regular object
|
|
1598
|
+
if (rest.isUnset) {
|
|
1599
|
+
return {
|
|
1600
|
+
type: 'object',
|
|
1601
|
+
...rest,
|
|
1602
|
+
...commonProps
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
return {
|
|
1606
|
+
type: 'unresolved_reference',
|
|
1607
|
+
refType: refType === 'asset' ? 'image' : 'object',
|
|
1608
|
+
...rest,
|
|
1609
|
+
...commonProps
|
|
1610
|
+
};
|
|
1611
|
+
} else if (docFieldLocalized.type === 'list') {
|
|
1612
|
+
const { items, ...rest } = docFieldLocalized;
|
|
1613
|
+
return {
|
|
1614
|
+
...rest,
|
|
1615
|
+
...commonProps,
|
|
1616
|
+
items: items.map((field) => toLocalizedAPIField(field, locale, true))
|
|
1617
|
+
};
|
|
1618
|
+
} else {
|
|
1619
|
+
return {
|
|
1620
|
+
...docFieldLocalized,
|
|
1621
|
+
...commonProps
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
function mapAssetsToLocalizedApiImages(assets: ContentStoreTypes.Asset[], locale?: string): ContentStoreTypes.APIImageObject[] {
|
|
1627
|
+
return assets.map((asset) => assetToLocalizedApiImage(asset, locale));
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
function assetToLocalizedApiImage(asset: ContentStoreTypes.Asset, locale?: string): ContentStoreTypes.APIImageObject {
|
|
1631
|
+
const { type, fields, ...rest } = asset;
|
|
1632
|
+
return {
|
|
1633
|
+
type: 'image',
|
|
1634
|
+
...rest,
|
|
1635
|
+
fields: localizeAssetFields(fields, locale)
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
function localizeAssetFields(assetFields: ContentStoreTypes.AssetFields, locale?: string): ContentStoreTypes.AssetFieldsAPI {
|
|
1640
|
+
const fields: ContentStoreTypes.AssetFieldsAPI = {
|
|
1641
|
+
title: {
|
|
1642
|
+
type: 'string' as const,
|
|
1643
|
+
value: null as any
|
|
1644
|
+
},
|
|
1645
|
+
url: {
|
|
1646
|
+
type: 'string' as const,
|
|
1647
|
+
value: null as any
|
|
1648
|
+
}
|
|
1649
|
+
};
|
|
1650
|
+
const titleFieldNonLocalized = getDocumentFieldForLocale(assetFields.title, locale);
|
|
1651
|
+
fields.title.value = titleFieldNonLocalized?.value;
|
|
1652
|
+
fields.title.locale = locale ?? titleFieldNonLocalized?.locale;
|
|
1653
|
+
const assetFileField = assetFields.file;
|
|
1654
|
+
if (assetFileField.localized) {
|
|
1655
|
+
if (locale) {
|
|
1656
|
+
fields.url.value = assetFileField.locales[locale]?.url ?? null;
|
|
1657
|
+
fields.url.locale = locale;
|
|
1658
|
+
}
|
|
1659
|
+
} else {
|
|
1660
|
+
fields.url.value = assetFileField.url;
|
|
1661
|
+
fields.url.locale = assetFileField.locale;
|
|
1662
|
+
}
|
|
1663
|
+
return fields;
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
function mapStoreAssetsToAPIAssets(assets: ContentStoreTypes.Asset[], locale?: string): ContentStoreTypes.APIAsset[] {
|
|
1667
|
+
return assets.map((asset) => storeAssetToAPIAsset(asset, locale));
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
function storeAssetToAPIAsset(asset: ContentStoreTypes.Asset, locale?: string): ContentStoreTypes.APIAsset {
|
|
1671
|
+
const assetTitleField = asset.fields.title;
|
|
1672
|
+
const localizedTitleField = assetTitleField.localized ? assetTitleField.locales[locale!]! : assetTitleField;
|
|
1673
|
+
const assetFileField = asset.fields.file;
|
|
1674
|
+
const localizedFileField = assetFileField.localized ? assetFileField.locales[locale!]! : assetFileField;
|
|
1675
|
+
return {
|
|
1676
|
+
objectId: asset.srcObjectId,
|
|
1677
|
+
createdAt: asset.createdAt,
|
|
1678
|
+
url: localizedFileField.url,
|
|
1679
|
+
...omitByNil({
|
|
1680
|
+
title: localizedTitleField.value,
|
|
1681
|
+
fileName: localizedFileField.fileName,
|
|
1682
|
+
contentType: localizedFileField.contentType,
|
|
1683
|
+
size: localizedFileField.size,
|
|
1684
|
+
width: localizedFileField.dimensions?.width,
|
|
1685
|
+
height: localizedFileField.dimensions?.height
|
|
1686
|
+
})
|
|
1687
|
+
};
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
/**
|
|
1691
|
+
* Iterates recursively objects with $$type and $$ref, creating nested objects
|
|
1692
|
+
* as needed and returns standard ContentSourceInterface Documents
|
|
1693
|
+
*/
|
|
1694
|
+
async function createDocumentRecursively({
|
|
1695
|
+
object,
|
|
1696
|
+
model,
|
|
1697
|
+
modelMap,
|
|
1698
|
+
locale,
|
|
1699
|
+
userContext,
|
|
1700
|
+
contentSourceInstance
|
|
1701
|
+
}: {
|
|
1702
|
+
object?: Record<string, any>;
|
|
1703
|
+
model: Model;
|
|
1704
|
+
modelMap: Record<string, Model>;
|
|
1705
|
+
locale?: string;
|
|
1706
|
+
userContext: unknown;
|
|
1707
|
+
contentSourceInstance: CSITypes.ContentSourceInterface;
|
|
1708
|
+
}): Promise<{ document: CSITypes.Document; newRefDocuments: CSITypes.Document[] }> {
|
|
1709
|
+
if (model.type === 'page') {
|
|
1710
|
+
const tokens = extractTokensFromString(String(model.urlPath));
|
|
1711
|
+
const slugField = _.last(tokens);
|
|
1712
|
+
if (object && slugField && slugField in object) {
|
|
1713
|
+
const slugFieldValue = object[slugField];
|
|
1714
|
+
object[slugField] = sanitizeSlug(slugFieldValue);
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
const nestedResult = await createNestedObjectRecursively({
|
|
1719
|
+
object,
|
|
1720
|
+
modelFields: model.fields ?? [],
|
|
1721
|
+
fieldPath: [],
|
|
1722
|
+
modelMap,
|
|
1723
|
+
locale,
|
|
1724
|
+
userContext,
|
|
1725
|
+
contentSourceInstance
|
|
1726
|
+
});
|
|
1727
|
+
const document = await contentSourceInstance.createDocument({
|
|
1728
|
+
documentFields: nestedResult.fields,
|
|
1729
|
+
model,
|
|
1730
|
+
modelMap,
|
|
1731
|
+
locale,
|
|
1732
|
+
userContext
|
|
1733
|
+
});
|
|
1734
|
+
return {
|
|
1735
|
+
document: document,
|
|
1736
|
+
newRefDocuments: nestedResult.newRefDocuments
|
|
1737
|
+
};
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
async function createNestedObjectRecursively({
|
|
1741
|
+
object,
|
|
1742
|
+
modelFields,
|
|
1743
|
+
fieldPath,
|
|
1744
|
+
modelMap,
|
|
1745
|
+
locale,
|
|
1746
|
+
userContext,
|
|
1747
|
+
contentSourceInstance
|
|
1748
|
+
}: {
|
|
1749
|
+
object?: Record<string, any>;
|
|
1750
|
+
modelFields: Field[];
|
|
1751
|
+
fieldPath: (string | number)[];
|
|
1752
|
+
modelMap: Record<string, Model>;
|
|
1753
|
+
locale?: string;
|
|
1754
|
+
userContext: unknown;
|
|
1755
|
+
contentSourceInstance: CSITypes.ContentSourceInterface;
|
|
1756
|
+
}): Promise<{
|
|
1757
|
+
fields: Record<string, CSITypes.UpdateOperationField>;
|
|
1758
|
+
newRefDocuments: CSITypes.Document[];
|
|
1759
|
+
}> {
|
|
1760
|
+
object = object ?? {};
|
|
1761
|
+
const result: {
|
|
1762
|
+
fields: Record<string, CSITypes.UpdateOperationField>;
|
|
1763
|
+
newRefDocuments: CSITypes.Document[];
|
|
1764
|
+
} = {
|
|
1765
|
+
fields: {},
|
|
1766
|
+
newRefDocuments: []
|
|
1767
|
+
};
|
|
1768
|
+
const objectFieldNames = Object.keys(object);
|
|
1769
|
+
for (const modelField of modelFields) {
|
|
1770
|
+
const fieldName = modelField.name;
|
|
1771
|
+
let value;
|
|
1772
|
+
if (fieldName in object) {
|
|
1773
|
+
value = object[fieldName];
|
|
1774
|
+
_.pull(objectFieldNames, fieldName);
|
|
1775
|
+
} else if (modelField.const) {
|
|
1776
|
+
value = modelField.const;
|
|
1777
|
+
} else if (!_.isNil(modelField.default)) {
|
|
1778
|
+
value = modelField.default;
|
|
1779
|
+
}
|
|
1780
|
+
if (!_.isNil(value)) {
|
|
1781
|
+
const fieldResult = await createNestedField({
|
|
1782
|
+
value,
|
|
1783
|
+
modelField,
|
|
1784
|
+
fieldPath: fieldPath.concat(fieldName),
|
|
1785
|
+
modelMap,
|
|
1786
|
+
locale,
|
|
1787
|
+
userContext,
|
|
1788
|
+
contentSourceInstance
|
|
1789
|
+
});
|
|
1790
|
+
result.fields[fieldName] = fieldResult.field;
|
|
1791
|
+
result.newRefDocuments = result.newRefDocuments.concat(fieldResult.newRefDocuments);
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
if (objectFieldNames.length > 0) {
|
|
1795
|
+
throw new Error(`no model fields found when creating a document with fields: '${objectFieldNames.join(', ')}'`);
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
return result;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
async function createNestedField({
|
|
1802
|
+
value,
|
|
1803
|
+
modelField,
|
|
1804
|
+
fieldPath,
|
|
1805
|
+
modelMap,
|
|
1806
|
+
locale,
|
|
1807
|
+
userContext,
|
|
1808
|
+
contentSourceInstance
|
|
1809
|
+
}: {
|
|
1810
|
+
value: any;
|
|
1811
|
+
modelField: FieldSpecificProps;
|
|
1812
|
+
fieldPath: (string | number)[];
|
|
1813
|
+
modelMap: Record<string, Model>;
|
|
1814
|
+
locale?: string;
|
|
1815
|
+
userContext: unknown;
|
|
1816
|
+
contentSourceInstance: CSITypes.ContentSourceInterface;
|
|
1817
|
+
}): Promise<{ field: CSITypes.UpdateOperationField; newRefDocuments: CSITypes.Document[] }> {
|
|
1818
|
+
if (modelField.type === 'object') {
|
|
1819
|
+
const result = await createNestedObjectRecursively({
|
|
1820
|
+
object: value,
|
|
1821
|
+
modelFields: modelField.fields,
|
|
1822
|
+
fieldPath,
|
|
1823
|
+
modelMap,
|
|
1824
|
+
locale,
|
|
1825
|
+
userContext,
|
|
1826
|
+
contentSourceInstance
|
|
1827
|
+
});
|
|
1828
|
+
return {
|
|
1829
|
+
field: {
|
|
1830
|
+
type: 'object',
|
|
1831
|
+
fields: result.fields
|
|
1832
|
+
},
|
|
1833
|
+
newRefDocuments: result.newRefDocuments
|
|
1834
|
+
};
|
|
1835
|
+
} else if (modelField.type === 'model') {
|
|
1836
|
+
let { $$type, ...rest } = value;
|
|
1837
|
+
const modelNames = modelField.models;
|
|
1838
|
+
// for backward compatibility check if the object has 'type' instead of '$$type' because older projects use
|
|
1839
|
+
// the 'type' property in default values
|
|
1840
|
+
if (!$$type && 'type' in rest) {
|
|
1841
|
+
$$type = rest.type;
|
|
1842
|
+
rest = _.omit(rest, 'type');
|
|
1843
|
+
}
|
|
1844
|
+
const modelName = $$type ?? (modelNames.length === 1 ? modelNames[0] : null);
|
|
1845
|
+
if (!modelName) {
|
|
1846
|
+
throw new Error(`no $$type was specified for nested model`);
|
|
1847
|
+
}
|
|
1848
|
+
const model = modelMap[modelName];
|
|
1849
|
+
if (!model) {
|
|
1850
|
+
throw new Error(`no model with name '${modelName}' was found`);
|
|
1851
|
+
}
|
|
1852
|
+
const result = await createNestedObjectRecursively({
|
|
1853
|
+
object: rest,
|
|
1854
|
+
modelFields: model.fields ?? [],
|
|
1855
|
+
fieldPath,
|
|
1856
|
+
modelMap,
|
|
1857
|
+
locale,
|
|
1858
|
+
userContext,
|
|
1859
|
+
contentSourceInstance
|
|
1860
|
+
});
|
|
1861
|
+
return {
|
|
1862
|
+
field: {
|
|
1863
|
+
type: 'model',
|
|
1864
|
+
modelName: modelName,
|
|
1865
|
+
fields: result.fields
|
|
1866
|
+
},
|
|
1867
|
+
newRefDocuments: result.newRefDocuments
|
|
1868
|
+
};
|
|
1869
|
+
} else if (modelField.type === 'image') {
|
|
1870
|
+
let refId: string | undefined;
|
|
1871
|
+
if (_.isPlainObject(value)) {
|
|
1872
|
+
refId = value.$$ref;
|
|
1873
|
+
} else {
|
|
1874
|
+
refId = value;
|
|
1875
|
+
}
|
|
1876
|
+
if (!refId) {
|
|
1877
|
+
throw new Error(`reference field must specify a value`);
|
|
1878
|
+
}
|
|
1879
|
+
return {
|
|
1880
|
+
field: {
|
|
1881
|
+
type: 'reference',
|
|
1882
|
+
refType: 'asset',
|
|
1883
|
+
refId: refId
|
|
1884
|
+
},
|
|
1885
|
+
newRefDocuments: []
|
|
1886
|
+
};
|
|
1887
|
+
} else if (modelField.type === 'reference') {
|
|
1888
|
+
let { $$ref: refId = null, $$type: modelName = null, ...rest } = _.isPlainObject(value) ? value : { $$ref: value };
|
|
1889
|
+
if (refId) {
|
|
1890
|
+
return {
|
|
1891
|
+
field: {
|
|
1892
|
+
type: 'reference',
|
|
1893
|
+
refType: 'document',
|
|
1894
|
+
refId: refId
|
|
1895
|
+
},
|
|
1896
|
+
newRefDocuments: []
|
|
1897
|
+
};
|
|
1898
|
+
} else {
|
|
1899
|
+
const modelNames = modelField.models;
|
|
1900
|
+
if (!modelName) {
|
|
1901
|
+
// for backward compatibility check if the object has 'type' instead of '$$type' because older projects use
|
|
1902
|
+
// the 'type' property in default values
|
|
1903
|
+
if ('type' in rest) {
|
|
1904
|
+
modelName = rest.type;
|
|
1905
|
+
rest = _.omit(rest, 'type');
|
|
1906
|
+
} else if (modelNames.length === 1) {
|
|
1907
|
+
modelName = modelNames[0];
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
const model = modelMap[modelName];
|
|
1911
|
+
if (!model) {
|
|
1912
|
+
throw new Error(`no model with name '${modelName}' was found`);
|
|
1913
|
+
}
|
|
1914
|
+
const { document, newRefDocuments } = await createDocumentRecursively({
|
|
1915
|
+
object: rest,
|
|
1916
|
+
model: model,
|
|
1917
|
+
modelMap,
|
|
1918
|
+
locale,
|
|
1919
|
+
userContext,
|
|
1920
|
+
contentSourceInstance
|
|
1921
|
+
});
|
|
1922
|
+
return {
|
|
1923
|
+
field: {
|
|
1924
|
+
type: 'reference',
|
|
1925
|
+
refType: 'document',
|
|
1926
|
+
refId: document.id
|
|
1927
|
+
},
|
|
1928
|
+
newRefDocuments: [document, ...newRefDocuments]
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
} else if (modelField.type === 'list') {
|
|
1932
|
+
if (!Array.isArray(value)) {
|
|
1933
|
+
throw new Error(`value for list field must be array`);
|
|
1934
|
+
}
|
|
1935
|
+
const itemsField = modelField.items;
|
|
1936
|
+
if (!itemsField) {
|
|
1937
|
+
throw new Error(`list field does not define items`);
|
|
1938
|
+
}
|
|
1939
|
+
const arrayResult = await mapPromise(value, async (item, index) => {
|
|
1940
|
+
return createNestedField({
|
|
1941
|
+
value: item,
|
|
1942
|
+
modelField: itemsField,
|
|
1943
|
+
fieldPath: fieldPath.concat(index),
|
|
1944
|
+
modelMap,
|
|
1945
|
+
locale,
|
|
1946
|
+
userContext,
|
|
1947
|
+
contentSourceInstance
|
|
1948
|
+
});
|
|
1949
|
+
});
|
|
1950
|
+
return {
|
|
1951
|
+
field: {
|
|
1952
|
+
type: 'list',
|
|
1953
|
+
items: arrayResult.map((result) => result.field)
|
|
1954
|
+
},
|
|
1955
|
+
newRefDocuments: arrayResult.reduce((result: CSITypes.Document[], { newRefDocuments }) => result.concat(newRefDocuments), [])
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
return {
|
|
1959
|
+
field: {
|
|
1960
|
+
type: modelField.type,
|
|
1961
|
+
value: value
|
|
1962
|
+
},
|
|
1963
|
+
newRefDocuments: []
|
|
1964
|
+
};
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
function getModelFieldForFieldAtPath(
|
|
1968
|
+
document: ContentStoreTypes.Document,
|
|
1969
|
+
model: Model,
|
|
1970
|
+
fieldPath: (string | number)[],
|
|
1971
|
+
modelMap: Record<string, Model>,
|
|
1972
|
+
locale?: string
|
|
1973
|
+
): Field {
|
|
1974
|
+
if (_.isEmpty(fieldPath)) {
|
|
1975
|
+
throw new Error('the fieldPath can not be empty');
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
function getField(docField: ContentStoreTypes.DocumentField, modelField: FieldSpecificProps, fieldPath: (string | number)[]): Field {
|
|
1979
|
+
const fieldName = _.head(fieldPath);
|
|
1980
|
+
if (typeof fieldName === 'undefined') {
|
|
1981
|
+
throw new Error('the first fieldPath item must be string');
|
|
1982
|
+
}
|
|
1983
|
+
const childFieldPath = _.tail(fieldPath);
|
|
1984
|
+
let childDocField: ContentStoreTypes.DocumentField | undefined;
|
|
1985
|
+
let childModelField: Field | undefined;
|
|
1986
|
+
switch (docField.type) {
|
|
1987
|
+
case 'object':
|
|
1988
|
+
const localizedObjectField = getDocumentFieldForLocale(docField, locale);
|
|
1989
|
+
if (!localizedObjectField) {
|
|
1990
|
+
throw new Error(`locale for field was not found`);
|
|
1991
|
+
}
|
|
1992
|
+
if (localizedObjectField.isUnset) {
|
|
1993
|
+
throw new Error(`field is not set`);
|
|
1994
|
+
}
|
|
1995
|
+
childDocField = localizedObjectField.fields[fieldName];
|
|
1996
|
+
childModelField = _.find((modelField as FieldObjectProps).fields, (field) => field.name === fieldName);
|
|
1997
|
+
if (!childDocField || !childModelField) {
|
|
1998
|
+
throw new Error(`field ${fieldName} doesn't exist`);
|
|
1999
|
+
}
|
|
2000
|
+
if (childFieldPath.length === 0) {
|
|
2001
|
+
return childModelField;
|
|
2002
|
+
}
|
|
2003
|
+
return getField(childDocField, childModelField, childFieldPath);
|
|
2004
|
+
case 'model':
|
|
2005
|
+
const localizedModelField = getDocumentFieldForLocale(docField, locale);
|
|
2006
|
+
if (!localizedModelField) {
|
|
2007
|
+
throw new Error(`locale for field was not found`);
|
|
2008
|
+
}
|
|
2009
|
+
if (localizedModelField.isUnset) {
|
|
2010
|
+
throw new Error(`field is not set`);
|
|
2011
|
+
}
|
|
2012
|
+
const modelName = localizedModelField.srcModelName;
|
|
2013
|
+
const childModel = modelMap[modelName];
|
|
2014
|
+
if (!childModel) {
|
|
2015
|
+
throw new Error(`model ${modelName} doesn't exist`);
|
|
2016
|
+
}
|
|
2017
|
+
childModelField = _.find(childModel.fields, (field) => field.name === fieldName);
|
|
2018
|
+
childDocField = localizedModelField.fields![fieldName];
|
|
2019
|
+
if (!childDocField || !childModelField) {
|
|
2020
|
+
throw new Error(`field ${fieldName} doesn't exist`);
|
|
2021
|
+
}
|
|
2022
|
+
if (childFieldPath.length === 0) {
|
|
2023
|
+
return childModelField;
|
|
2024
|
+
}
|
|
2025
|
+
return getField(childDocField, childModelField!, childFieldPath);
|
|
2026
|
+
case 'list':
|
|
2027
|
+
const localizedListField = getDocumentFieldForLocale(docField, locale);
|
|
2028
|
+
if (!localizedListField) {
|
|
2029
|
+
throw new Error(`locale for field was not found`);
|
|
2030
|
+
}
|
|
2031
|
+
const listItem = localizedListField.items && localizedListField.items[fieldName as number];
|
|
2032
|
+
const listItemsModel = (modelField as FieldListProps).items;
|
|
2033
|
+
if (!listItem || !listItemsModel) {
|
|
2034
|
+
throw new Error(`field ${fieldName} doesn't exist`);
|
|
2035
|
+
}
|
|
2036
|
+
if (childFieldPath.length === 0) {
|
|
2037
|
+
return modelField as FieldList;
|
|
2038
|
+
}
|
|
2039
|
+
if (!Array.isArray(listItemsModel)) {
|
|
2040
|
+
return getField(listItem, listItemsModel, childFieldPath);
|
|
2041
|
+
} else {
|
|
2042
|
+
const fieldListItems = (listItemsModel as FieldListItems[]).find((listItemsModel) => listItemsModel.type === listItem.type);
|
|
2043
|
+
if (!fieldListItems) {
|
|
2044
|
+
throw new Error('cannot find matching field model');
|
|
2045
|
+
}
|
|
2046
|
+
return getField(listItem, fieldListItems, childFieldPath);
|
|
2047
|
+
}
|
|
2048
|
+
default:
|
|
2049
|
+
if (!_.isEmpty(childFieldPath)) {
|
|
2050
|
+
throw new Error('illegal fieldPath');
|
|
2051
|
+
}
|
|
2052
|
+
return modelField as Field;
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
const fieldName = _.head(fieldPath);
|
|
2057
|
+
const childFieldPath = _.tail(fieldPath);
|
|
2058
|
+
|
|
2059
|
+
if (typeof fieldName !== 'string') {
|
|
2060
|
+
throw new Error('the first fieldPath item must be string');
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
const childDocField = document.fields[fieldName];
|
|
2064
|
+
const childModelField = _.find(model.fields, { name: fieldName });
|
|
2065
|
+
|
|
2066
|
+
if (!childDocField || !childModelField) {
|
|
2067
|
+
throw new Error(`field ${fieldName} doesn't exist`);
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
if (childFieldPath.length === 0) {
|
|
2071
|
+
return childModelField;
|
|
2072
|
+
}
|
|
2073
|
+
|
|
2074
|
+
return getField(childDocField, childModelField, childFieldPath);
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
async function convertOperationField({
|
|
2078
|
+
operationField,
|
|
2079
|
+
fieldPath,
|
|
2080
|
+
modelField,
|
|
2081
|
+
modelMap,
|
|
2082
|
+
locale,
|
|
2083
|
+
userContext,
|
|
2084
|
+
contentSourceInstance
|
|
2085
|
+
}: {
|
|
2086
|
+
operationField: ContentStoreTypes.UpdateOperationField;
|
|
2087
|
+
fieldPath: (string | number)[];
|
|
2088
|
+
modelField: Field;
|
|
2089
|
+
modelMap: Record<string, Model>;
|
|
2090
|
+
locale?: string;
|
|
2091
|
+
userContext: unknown;
|
|
2092
|
+
contentSourceInstance: CSITypes.ContentSourceInterface;
|
|
2093
|
+
}): Promise<CSITypes.UpdateOperationField> {
|
|
2094
|
+
// for insert operations, the modelField will be of the list, so get the modelField of the list items
|
|
2095
|
+
const modelFieldOrListItems: FieldSpecificProps = modelField.type === 'list' ? modelField.items! : modelField;
|
|
2096
|
+
switch (operationField.type) {
|
|
2097
|
+
case 'object': {
|
|
2098
|
+
const result = await createNestedObjectRecursively({
|
|
2099
|
+
object: operationField.object,
|
|
2100
|
+
modelFields: (modelFieldOrListItems as FieldObjectProps).fields,
|
|
2101
|
+
fieldPath: fieldPath,
|
|
2102
|
+
modelMap,
|
|
2103
|
+
locale,
|
|
2104
|
+
userContext,
|
|
2105
|
+
contentSourceInstance
|
|
2106
|
+
});
|
|
2107
|
+
return {
|
|
2108
|
+
type: operationField.type,
|
|
2109
|
+
fields: result.fields
|
|
2110
|
+
};
|
|
2111
|
+
}
|
|
2112
|
+
case 'model': {
|
|
2113
|
+
const model = modelMap[operationField.modelName];
|
|
2114
|
+
if (!model) {
|
|
2115
|
+
throw new Error(`error updating document, could not find document model: '${operationField.modelName}'`);
|
|
2116
|
+
}
|
|
2117
|
+
const result = await createNestedObjectRecursively({
|
|
2118
|
+
object: operationField.object,
|
|
2119
|
+
modelFields: model.fields!,
|
|
2120
|
+
fieldPath,
|
|
2121
|
+
modelMap,
|
|
2122
|
+
locale,
|
|
2123
|
+
userContext,
|
|
2124
|
+
contentSourceInstance
|
|
2125
|
+
});
|
|
2126
|
+
return {
|
|
2127
|
+
type: operationField.type,
|
|
2128
|
+
modelName: operationField.modelName,
|
|
2129
|
+
fields: result.fields
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
case 'list': {
|
|
2133
|
+
if (modelField.type !== 'list') {
|
|
2134
|
+
throw new Error(`'the operation field type '${operationField.type}' does not match the model field type '${modelField.type}'`);
|
|
2135
|
+
}
|
|
2136
|
+
const result = await mapPromise(operationField.items, async (item, index) => {
|
|
2137
|
+
const result = await createNestedField({
|
|
2138
|
+
value: item,
|
|
2139
|
+
modelField: modelField.items!,
|
|
2140
|
+
fieldPath,
|
|
2141
|
+
modelMap,
|
|
2142
|
+
locale,
|
|
2143
|
+
userContext,
|
|
2144
|
+
contentSourceInstance
|
|
2145
|
+
});
|
|
2146
|
+
return result.field;
|
|
2147
|
+
});
|
|
2148
|
+
return {
|
|
2149
|
+
type: operationField.type,
|
|
2150
|
+
items: result
|
|
2151
|
+
};
|
|
2152
|
+
}
|
|
2153
|
+
case 'string':
|
|
2154
|
+
if (typeof operationField.value !== 'string') {
|
|
2155
|
+
return {
|
|
2156
|
+
type: operationField.type,
|
|
2157
|
+
value: ''
|
|
2158
|
+
};
|
|
2159
|
+
}
|
|
2160
|
+
return operationField as CSITypes.UpdateOperationField;
|
|
2161
|
+
case 'enum':
|
|
2162
|
+
if (typeof operationField.value !== 'string') {
|
|
2163
|
+
if (modelFieldOrListItems.type !== 'enum') {
|
|
2164
|
+
throw new Error(`'the operation field type 'enum' does not match the model field type '${modelFieldOrListItems.type}'`);
|
|
2165
|
+
}
|
|
2166
|
+
const option = modelFieldOrListItems.options[0]!;
|
|
2167
|
+
const optionValue = typeof option === 'object' ? option.value : option;
|
|
2168
|
+
return {
|
|
2169
|
+
type: operationField.type,
|
|
2170
|
+
value: optionValue
|
|
2171
|
+
};
|
|
2172
|
+
}
|
|
2173
|
+
return operationField as CSITypes.UpdateOperationField;
|
|
2174
|
+
case 'image':
|
|
2175
|
+
if (typeof operationField.value !== 'string') {
|
|
2176
|
+
throw new Error('image value was not specified');
|
|
2177
|
+
}
|
|
2178
|
+
return operationField as CSITypes.UpdateOperationField;
|
|
2179
|
+
default:
|
|
2180
|
+
return operationField as CSITypes.UpdateOperationField;
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
function getDocumentFieldForLocale<Type extends ContentStoreTypes.FieldType>(
|
|
2185
|
+
docField: ContentStoreTypes.DocumentFieldForType<Type>,
|
|
2186
|
+
locale?: string
|
|
2187
|
+
): ContentStoreTypes.DocumentFieldNonLocalizedForType<Type> | null {
|
|
2188
|
+
if (docField.localized) {
|
|
2189
|
+
if (!locale) {
|
|
2190
|
+
return null;
|
|
2191
|
+
}
|
|
2192
|
+
const { localized, locales, ...base } = docField;
|
|
2193
|
+
const localizedField = locales[locale];
|
|
2194
|
+
if (!localizedField) {
|
|
2195
|
+
return null;
|
|
2196
|
+
}
|
|
2197
|
+
return ({
|
|
2198
|
+
...base,
|
|
2199
|
+
...localizedField
|
|
2200
|
+
} as unknown) as ContentStoreTypes.DocumentFieldNonLocalizedForType<Type>;
|
|
2201
|
+
} else {
|
|
2202
|
+
return docField;
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
function isStackbitConfigFile(filePath: string) {
|
|
2207
|
+
const pathObject = path.parse(filePath);
|
|
2208
|
+
const isInDotStackbitFolder = pathObject.dir.startsWith('.stackbit');
|
|
2209
|
+
const isMainStackbitConfigFile = pathObject.name === 'stackbit' && ['yaml', 'yml'].includes(pathObject.ext.substring(1));
|
|
2210
|
+
return isMainStackbitConfigFile || isInDotStackbitFolder;
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
function getCSIDocumentsAndAssetsFromContentSourceDataByIds(
|
|
2214
|
+
contentSourceData: ContentSourceData,
|
|
2215
|
+
objects: { srcObjectId: string }[]
|
|
2216
|
+
): {
|
|
2217
|
+
documents: CSITypes.Document[];
|
|
2218
|
+
assets: CSITypes.Asset[];
|
|
2219
|
+
} {
|
|
2220
|
+
const documents: CSITypes.Document[] = [];
|
|
2221
|
+
const assets: CSITypes.Asset[] = [];
|
|
2222
|
+
for (const object of objects) {
|
|
2223
|
+
if (object.srcObjectId in contentSourceData.csiDocumentMap) {
|
|
2224
|
+
documents.push(contentSourceData.csiDocumentMap[object.srcObjectId]!);
|
|
2225
|
+
} else if (object.srcObjectId in contentSourceData.csiAssetMap) {
|
|
2226
|
+
assets.push(contentSourceData.csiAssetMap[object.srcObjectId]!);
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
return {
|
|
2230
|
+
documents,
|
|
2231
|
+
assets
|
|
2232
|
+
};
|
|
2233
|
+
}
|