-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathentity.ts
350 lines (316 loc) · 11.1 KB
/
entity.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/* eslint-disable max-classes-per-file */
import { equal, isNullish } from '@sap-cloud-sdk/util';
import { EntityBuilder } from './entity-builder';
import { Link, Field, Selectable, CustomFieldBase } from './selectable';
import { RequestBuilder } from './request-builder';
import { isNavigationProperty, nonEnumerable } from './properties-util';
import { toPropertyFormat } from './name-converter';
export type ODataVersionOf<T extends EntityBase> = T['_oDataVersion'];
/**
* @hidden
*/
export interface Constructable<
EntityT extends EntityBase,
EntityTypeT = unknown
> {
_serviceName: string;
_entityName: string;
_defaultServicePath: string;
_allFields: (Selectable<EntityT> | Field<EntityT> | Link<EntityT>)[]; // Selectable only here for backwards TODO: Remove in v2.0
_keyFields: (Selectable<EntityT> | Field<EntityT>)[]; // Selectable only here for backwards TODO: Remove in v2.0
_keys: { [keys: string]: Selectable<EntityT> | Field<EntityT> }; // Selectable only here for backwards TODO: Remove in v2.0
new (...args: any[]): EntityT;
requestBuilder(): RequestBuilder<EntityT>;
builder(): EntityBuilderType<EntityT, EntityTypeT>;
customField(fieldName: string): CustomFieldBase<EntityT>;
}
export type EntityBuilderType<EntityT extends EntityBase, EntityTypeT> = {
[property in keyof Required<EntityTypeT>]: (
value: EntityTypeT[property]
) => EntityBuilderType<EntityT, EntityTypeT>;
} &
EntityBuilder<EntityT, EntityTypeT>;
/**
* Super class for all representations of OData entity types.
*/
export abstract class EntityBase {
static _serviceName: string;
static _entityName: string;
static _defaultServicePath: string;
protected static entityBuilder<EntityT extends EntityBase, EntityTypeT>(
entityConstructor: Constructable<EntityT, EntityTypeT>
): EntityBuilderType<EntityT, EntityTypeT> {
const builder = new EntityBuilder<EntityT, EntityTypeT>(entityConstructor);
entityConstructor._allFields.forEach(field => {
const fieldName = `${toPropertyFormat(field._fieldName)}`;
builder[fieldName] = function (value) {
this.entity[fieldName] = value;
return this;
};
});
return builder as EntityBuilderType<EntityT, EntityTypeT>;
}
/**
* The remote state of the entity.
* Remote state refers to the last known state of the entity on the remote system from which it has been retrieved or to which it has been posted.
* It is stored as map, where the keys are stored in the format of the original OData properties.
*/
protected remoteState: { [keys: string]: any };
/**
* The current ETag version of the entity in the remote system.
* The ETag identified the version of the in the remote system. It will be automatically set in the "if-match" header of update requests and can be set as a custom header for delete requests.
* When no ETag is provided by the remote system the value of this variable defaults to "*".
*/
protected _versionIdentifier: string;
/**
* A mapper representing custom fields in an entity.
* Custom fields are represented by their field names and the corresponding values.
* A custom field can be added or updated using [[setCustomField]] method.
*/
protected _customFields: Record<string, any>;
abstract readonly _oDataVersion: any;
constructor() {
nonEnumerable(this, '_oDataVersion');
nonEnumerable(this, '_customFields');
this._customFields = {};
}
/**
* ETag version identifier accessor.
*
* @returns The ETag version identifier of the retrieved entity, returns undefined if not retrieved
*/
get versionIdentifier(): string {
return this._versionIdentifier;
}
/**
* Returns a map that contains all entity custom fields.
*
* @returns A map of all defined custom fields in the entity
*/
getCustomFields(): Record<string, any> {
return this._customFields;
}
/**
* Custom field value getter.
*
* @param fieldName - The name of the custom field
* @returns The value of the corresponding custom field
*/
getCustomField(fieldName: string): any {
return this._customFields[fieldName];
}
/**
* Sets a new custom field in the entity or updates it.
* Throws an error, if the provided custom field name is already defined by an original field in entity.
*
* @param fieldName - The name of the custom field to update
* @param value - The value of the field
* @returns The entity itself, to facilitate method chaining
*/
setCustomField(fieldName: string, value: any): this {
if (this.isConflictingCustomField(fieldName)) {
throw new Error(
`The field name "${fieldName}" is already defined in the entity and cannot be set as custom field.`
);
}
this._customFields[fieldName] = value;
return this;
}
/**
* Validates whether a custom field exists in the entity.
*
* @param fieldName - The name of the custom field to update
* @returns A boolean value, that indicates whether a custom field is defined in entity
*/
hasCustomField(fieldName: string): boolean {
return this._customFields[fieldName] !== undefined;
}
/**
* Sets all retrieved custom fields in entity.
*
* @param customFields - Extracted custom fields from a retrieved entity
* @returns A boolean value, that indicates the existence of the field in entity
*/
initializeCustomFields(customFields: Record<string, any>): this {
Object.entries(customFields).forEach(cf => {
this.setCustomField(cf[0], cf[1]);
});
return this;
}
/**
* Set the ETag version identifier of the retrieved entity.
*
* @param etag - The returned ETag version of the entity
* @returns The entity itself, to facilitate method chaining
*/
public setVersionIdentifier(etag: string | undefined): this {
if (etag && typeof etag === 'string') {
nonEnumerable(this, '_versionIdentifier');
this._versionIdentifier = etag;
}
return this;
}
/**
* Initializes or sets the remoteState of the entity.
* This function is called on all read, create and update requests.
* This function should be called after [[initializeCustomFields]], if custom fields are defined.
*
* @deprecated Since 1.12.0. Will be hidden in version 2.0.
* @param state - State to be set as remote state
* @returns The entity itself, to facilitate method chaining
*/
public setOrInitializeRemoteState(state?: Record<string, any>): this {
if (!this.remoteState) {
nonEnumerable(this, 'remoteState');
this.remoteState = {};
}
if (state) {
Object.entries(state).forEach(([fieldName, value]) => {
if (this[toPropertyFormat(fieldName)]) {
this.remoteState[toPropertyFormat(fieldName)] = value;
} else {
// We store the custom field with its original name in the remote state
this.remoteState[fieldName] = value;
}
});
} else {
this.remoteState = this.getCurrentMapKeys();
}
return this;
}
/**
* Returns all updated custom field properties compared to the last known remote state.
*
* @returns A map containing all updated custom properties, with their new values
*/
public getUpdatedCustomFields(): Record<string, any> {
if (this.remoteState === undefined) {
return this._customFields;
}
return Object.entries(this.getCustomFields())
.filter(([fieldName, value]) => this.remoteState[fieldName] !== value)
.reduce(
(updatedCustomFields, [fieldName, value]) => ({
...updatedCustomFields,
[fieldName]: value
}),
{}
);
}
/**
* Returns all changed properties compared to the last known remote state.
* The returned properties does not include custom fields. Use [[getUpdatedCustomFields]], if updated custom fields are needed.
*
* @returns Entity with all properties that changed
*/
public getUpdatedProperties(): this {
const current = this.getCurrentMapKeys();
if (this.remoteState === undefined) {
return current;
}
const patch = {};
Object.keys(current)
.filter(key => this.propertyIsEnumerable(key))
.filter(key => !this.hasCustomField(key))
.forEach(key => {
if (!equal(this.remoteState[key], current[key])) {
patch[key] = current[key];
}
});
return patch as this;
}
/**
* Returns a map of all defined fields in entity to their current values.
* @param visitedEntities List of entities to check in case of circular dependencies.
* @returns Entity with all defined entity fields
*/
protected getCurrentMapKeys(visitedEntities: EntityBase[] = []): this {
visitedEntities.push(this);
return Object.keys(this)
.filter(key => this.propertyIsEnumerable(key))
.filter(
key =>
!isNavigationProperty(key, this.constructor) ||
!this.isVisitedEntity(this[key], visitedEntities)
)
.reduce(
(accumulatedMap, key) => ({
...accumulatedMap,
[key]: this.getCurrentStateForKey(key, visitedEntities)
}),
this.getCustomFields()
) as this;
}
protected isVisitedEntity<EntityT extends EntityBase>(
entity: EntityT,
visitedEntities: EntityBase[] = []
): boolean {
const isVisited = Array.isArray(entity)
? entity.some(multiLinkChild => visitedEntities.includes(multiLinkChild))
: visitedEntities.includes(entity);
return isVisited;
}
protected getCurrentStateForKey(
key: string,
visitedEntities: EntityBase[] = []
) {
if (isNavigationProperty(key, this.constructor)) {
if (isNullish(this[key])) {
return this[key];
}
return Array.isArray(this[key])
? this[key].map(linkedEntity =>
linkedEntity.getCurrentMapKeys(visitedEntities)
)
: this[key].getCurrentMapKeys(visitedEntities);
}
return Array.isArray(this[key]) ? [...this[key]] : this[key];
}
/**
* Validates whether a field name does not conflict with an original field name and thus can be defined as custom fields.
*
* @param customFieldName - Field name to check
* @returns Boolean value that describes whether a field name can be defined as custom field
*/
protected isConflictingCustomField(customFieldName: string): boolean {
return this[toPropertyFormat(customFieldName)] !== undefined;
}
}
/**
* @hidden
*/
export interface EntityIdentifiable<T extends EntityBase> {
readonly _entityConstructor: Constructable<T>;
readonly _entity: T;
}
/* eslint-disable valid-jsdoc */
/**
* @hidden
*/
export function isSelectedProperty<EntityT extends EntityBase>(
json,
field: Field<EntityT> | Link<EntityT>
) {
return json.hasOwnProperty(field._fieldName);
}
/**
* @hidden
*/
export function isExistentProperty<
EntityT extends EntityBase,
LinkedEntityT extends EntityBase
>(json, link: Link<EntityT, LinkedEntityT>) {
return isSelectedProperty(json, link) && json[link._fieldName] !== null;
}
/**
* @hidden
*/
export function isExpandedProperty<
EntityT extends EntityBase,
LinkedEntityT extends EntityBase
>(json, link: Link<EntityT, LinkedEntityT>) {
return (
isExistentProperty(json, link) &&
!json[link._fieldName].hasOwnProperty('__deferred')
);
}