/
get-keys.ts
31 lines (29 loc) · 1023 Bytes
/
get-keys.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
/* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */
import { EntityBase, Constructable } from '../entity';
import { toPropertyFormat } from '../../../util';
import { Field } from '../selectable';
/**
* Helper function that maps an entity to its keys map with their original names.
*
* @param entity - Entity to map
* @param entityConstructor - The constructor of the entity
* @returns object that includes all keys that represent given entity
*/
export function getEntityKeys<EntityT extends EntityBase>(
entity: EntityT,
entityConstructor: Constructable<EntityT>
): Record<string, any> {
if (!entity) {
throw new Error(
'getEntityKeys() cannot extract keys from an undefined or null object.'
);
}
// type assertion for backwards compatibility, TODO: remove in v2.0
return (entityConstructor._keyFields as Field<EntityT>[]).reduce(
(prev, curr) => ({
...prev,
[curr._fieldName]: entity[toPropertyFormat(curr._fieldName)]
}),
{}
);
}