-
Notifications
You must be signed in to change notification settings - Fork 114
/
entityHelpers.ts
322 lines (283 loc) · 7.39 KB
/
entityHelpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import get from 'lodash/get';
import isObject from 'lodash/isObject';
import { Asset, ContentType, ContentTypeField, Entry, File } from '../typesEntity';
function titleOrDefault(title: string | undefined, defaultTitle: string): string {
if (!(title != null && typeof title.valueOf() === 'string')) {
return defaultTitle;
}
if (title) {
const trimmedTitle = title.trim();
if (trimmedTitle.length === 0) {
return defaultTitle;
}
return trimmedTitle;
}
return defaultTitle;
}
export function getFieldValue({
/**
* Expects an entity fetched with a flag Skip-Transformation: true
*/
entity,
fieldId,
localeCode,
defaultLocaleCode,
}: {
entity: {
fields: { [key: string]: { [valueKey: string]: string | undefined } };
};
fieldId: string;
localeCode: string;
defaultLocaleCode: string;
}): string | undefined {
const values = get(entity, ['fields', fieldId]);
if (!isObject(values)) {
return;
}
const firstLocaleCode = Object.keys(values)[0];
return values[localeCode] || values[defaultLocaleCode] || values[firstLocaleCode];
}
export function getAssetTitle({
asset,
localeCode,
defaultLocaleCode,
defaultTitle,
}: {
asset: Asset;
localeCode: string;
defaultLocaleCode: string;
defaultTitle: string;
}) {
const title = getFieldValue({
entity: { fields: { title: asset.fields?.title } },
fieldId: 'title',
localeCode,
defaultLocaleCode,
});
return titleOrDefault(title, defaultTitle);
}
/**
* Returns true if field is an Asset
*
* @param field
* @returns {boolean}
*/
export const isAssetField = (field: ContentTypeField): boolean =>
field.type === 'Link' && field.linkType === 'Asset';
/**
* Returns true if field is a Title
*/
export function isDisplayField({
field,
contentType,
}: {
field: ContentTypeField;
contentType: ContentType;
}): boolean {
return field.id === contentType.displayField;
}
/**
* Returns true if field is a short Description
*/
export function isDescriptionField({
field,
contentType,
}: {
field: ContentTypeField;
contentType: ContentType;
}) {
const isTextField = (field: ContentTypeField) => ['Symbol', 'Text'].includes(field.type);
const isMaybeSlugField = (field: ContentTypeField) => /\bslug\b/.test(field.name);
return isTextField(field) && !isDisplayField({ field, contentType }) && !isMaybeSlugField(field);
}
export function getEntityDescription({
entity,
contentType,
localeCode,
defaultLocaleCode,
}: {
entity: Entry;
contentType?: ContentType;
localeCode: string;
defaultLocaleCode: string;
}): string {
if (!contentType) {
return '';
}
const descriptionField = contentType.fields.find((field) =>
isDescriptionField({ field, contentType })
);
if (!descriptionField) {
return '';
}
return (
getFieldValue({ entity, fieldId: descriptionField.id, localeCode, defaultLocaleCode }) || ''
);
}
export function getEntryTitle({
entry,
contentType,
localeCode,
defaultLocaleCode,
defaultTitle,
}: {
entry: Entry;
contentType?: ContentType;
localeCode: string;
defaultLocaleCode: string;
defaultTitle: string;
}) {
let title;
if (!contentType) {
return defaultTitle;
}
const displayField = contentType.displayField;
if (!displayField) {
return defaultTitle;
}
const displayFieldInfo = contentType.fields.find((field) => field.id === displayField);
if (!displayFieldInfo) {
return defaultTitle;
}
// when localization for a field is "turned off",
// we don't clean up the "old" localized data, so it is still in the response.
// Therefore, we're checking if displayField is localizable.
if (displayFieldInfo.localized) {
title = getFieldValue({
entity: entry,
fieldId: displayField,
localeCode,
defaultLocaleCode,
});
if (!title) {
// Older content types may return id/apiName, but some entry lookup paths do not fetch raw data
// In order to still return a title in this case, look for displayField as apiName in content type,
// ...but still look for displayField as a field in the entry
title = getFieldValue({
entity: entry,
fieldId: displayFieldInfo.id,
localeCode,
defaultLocaleCode,
});
}
} else {
title = getFieldValue({
entity: entry,
fieldId: displayField,
defaultLocaleCode,
localeCode: '',
});
if (!title) {
title = getFieldValue({
entity: entry,
fieldId: displayFieldInfo.id,
defaultLocaleCode,
localeCode: '',
});
}
}
return titleOrDefault(title, defaultTitle);
}
type AsyncPublishStatus = 'draft' | 'published' | 'changed';
type FieldStatus = {
'*': Record<string, AsyncPublishStatus>;
};
/**
* Returns the status of the entry/asset
* If a locale code(s) is provided it will pick up the most advanced state for these locale(s)
* - deleted
* - archived
* - changed
* - published
* - draft
*/
export function getEntityStatus(
sys: (Entry['sys'] | Asset['sys']) & { fieldStatus?: FieldStatus },
localeCodes?: string | string[]
) {
if (!sys || (sys.type !== 'Entry' && sys.type !== 'Asset')) {
throw new TypeError('Invalid entity metadata object');
}
if (sys.deletedVersion) {
return 'deleted';
}
if (sys.archivedVersion) {
return 'archived';
}
// TODO: remove the condition, once locale based publishing is GA
// Then we don't need the publishedVersion calculation anymore
if (sys.fieldStatus && localeCodes) {
let status: AsyncPublishStatus = 'draft';
const isMatchingLocale = (locale: string) => {
if (Array.isArray(localeCodes)) {
return localeCodes.includes(locale);
}
return localeCodes ? localeCodes === locale : true;
};
Object.entries(sys.fieldStatus['*']).forEach(([localeCode, fieldStatus]) => {
if (isMatchingLocale(localeCode)) {
if (fieldStatus === 'changed') {
status = fieldStatus;
return;
}
if (fieldStatus === 'published') {
status = fieldStatus;
}
}
});
return status;
}
if (sys.publishedVersion) {
if (sys.version > sys.publishedVersion + 1) {
return 'changed';
} else {
return 'published';
}
}
return 'draft';
}
/**@deprecated use `getEntityStatus` */
export function getEntryStatus(
//TODO: remove union after fieldStatus is added to App SDK
sys: Entry['sys'] & { fieldStatus?: FieldStatus },
localeCodes?: string | string[]
) {
return getEntityStatus(sys, localeCodes);
}
/**
* Gets a promise resolving with a localized asset image field representing a
* given entities file. The promise may resolve with null.
*/
export const getEntryImage = async (
{
entry,
contentType,
localeCode,
}: {
entry: Entry;
contentType?: ContentType;
localeCode: string;
defaultLocaleCode: string;
},
getAsset: (assetId: string) => Promise<unknown>
): Promise<null | File> => {
if (!contentType) {
return null;
}
const assetLink = contentType.fields.find(isAssetField);
if (!assetLink) {
return null;
}
const assetId = get(entry.fields, [assetLink.id, localeCode, 'sys', 'id']);
if (!assetId) {
return null;
}
try {
const asset = await getAsset(assetId);
const file = get(asset, ['fields', 'file', localeCode]);
const isImage = Boolean(get(file, ['details', 'image'], false));
return isImage ? file : null;
} catch (e) {
return null;
}
};