feat: add method to remove references from a thing

Fixes #6
This commit is contained in:
Karl-Philipp Wulfert
2019-04-02 18:04:38 +02:00
parent a3b16b8a37
commit 9cf6fde050
4 changed files with 142 additions and 2 deletions

View File

@@ -14,6 +14,8 @@
*/
import {asyncPool} from '@krlwlfrt/async-pool';
import {
isThing,
SCAssociatedThingWithoutReferences,
SCBulkResponse,
SCBulkRoute,
SCLicensePlate,
@@ -68,6 +70,76 @@ export class ConnectorClient extends Client {
return v5(uid.toString(), SCNamespaces[namespaceId]);
}
/**
* Remove fields from a thing that are references
*
* This effectively turns a thing into a thing without references, e.g. SCDish into SCDishWithoutReferences.
*
* @param thing Thing to remove references from
*/
static removeReferences<THING extends SCThings>(thing: THING): SCAssociatedThingWithoutReferences<THING> {
const thingWithoutReferences: any = {
...{},
...thing,
};
// iterate over all properties
for (const key in thingWithoutReferences) {
/* istanbul ignore if */
if (!thingWithoutReferences.hasOwnProperty(key)) {
continue;
}
const property = thingWithoutReferences[key];
// check if property itself is a thing
if (isThing(property)) {
// delete said property
delete thingWithoutReferences[key];
continue;
}
// check if property is an array
if (Array.isArray(property)) {
if (property.every(isThing)) {
// delete property if every item in it is a thing
delete thingWithoutReferences[key];
} else {
// check every item in array
for (const item of property) {
if (['boolean', 'number', 'string'].indexOf(typeof item) >= 0) {
// skip primitives
continue;
}
// check every property
for (const itemKey in item) {
/* istanbul ignore if */
if (!item.hasOwnProperty(itemKey)) {
continue;
}
if (isThing(item[itemKey])) {
// delete properties that are things
delete item[itemKey];
}
}
}
}
} else if (typeof property === 'object') {
// iterate over all properties in nested objects
for (const nestedKey in property) {
if (isThing(property[nestedKey])) {
// delete properties that are things
delete property[nestedKey];
}
}
}
}
return thingWithoutReferences as SCAssociatedThingWithoutReferences<THING>;
}
/**
* Request a bulk transfer to the backend
*