Skip to content

Commit

Permalink
Correct JSON Filtering on sub-objects with own filter
Browse files Browse the repository at this point in the history
  • Loading branch information
theimo1221 committed Oct 12, 2024
1 parent 90d8b7b commit 732fe7e
Show file tree
Hide file tree
Showing 10 changed files with 61 additions and 29 deletions.
9 changes: 9 additions & 0 deletions src/models/iJsonOmitKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* An object which defines certain keys to exclude from the JSON output
*/
export interface iJsonOmitKeys {
/**
* List of keys to exclude
*/
readonly jsonOmitKeys: string[];
}
1 change: 1 addition & 0 deletions src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ export * from './objectSettings';
export * from './temperatureSettings';
export * from './timeCallback';
export { BlockAutomaticSettings } from './blockAutomaticSettings';
export { iJsonOmitKeys } from './iJsonOmitKeys';
15 changes: 12 additions & 3 deletions src/server/devices/IoBrokerBaseDevice.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import { iRoomDevice } from './baseDeviceInterfaces';
import { API, LogDebugType, ServerLogService, Utils } from '../services';
import { DeviceSettings, LogLevel, RoomAddDeviceItem, RoomBase, RoomDeviceAddingSettings } from '../../models';
import {
DeviceSettings,
iJsonOmitKeys,
LogLevel,
RoomAddDeviceItem,
RoomBase,
RoomDeviceAddingSettings,
} from '../../models';
import { IOBrokerConnection, ioBrokerMain } from '../ioBroker';
import { DeviceType } from './deviceType';
import { IoBrokerDeviceInfo } from './IoBrokerDeviceInfo';
import { DeviceCapability } from './DeviceCapability';

export abstract class IoBrokerBaseDevice implements iRoomDevice {
export abstract class IoBrokerBaseDevice implements iRoomDevice, iJsonOmitKeys {
/** @inheritDoc */
public readonly jsonOmitKeys: string[] = ['individualStateCallbacks'];
/**
* The settings for adding devices to Rooms
*/
Expand Down Expand Up @@ -147,7 +156,7 @@ export abstract class IoBrokerBaseDevice implements iRoomDevice {

/** @inheritDoc */
public toJSON(): Partial<IoBrokerBaseDevice> {
return Utils.jsonFilter(this, ['individualStateCallbacks'], ['_room']);
return Utils.jsonFilter(this, this.jsonOmitKeys, ['_room']);
}

/** @inheritDoc */
Expand Down
5 changes: 0 additions & 5 deletions src/server/devices/dachs/dachsTemperatureSensor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,6 @@ export class DachsTemperatureSensor implements iTemperatureSensor {
this.roomTemperature = newTemperatur;
}

/** @inheritDoc */
public persistTemperaturSensor(): void {
this.temperatureSensor.persist();
}

/** @inheritDoc */
public log(level: LogLevel, message: string, debugType: LogDebugType = LogDebugType.None): void {
ServerLogService.writeLog(level, `${this.name}: ${message}`, {
Expand Down
13 changes: 8 additions & 5 deletions src/server/devices/sharedFunctions/battery.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { iBatteryDevice } from '../baseDeviceInterfaces';
import { Utils } from '../../services';
import { BatteryLevelChangeAction, VictronDeviceSettings } from '../../../models';
import { iJsonOmitKeys } from '../../../models/iJsonOmitKeys';

export class Battery {
export class Battery implements iJsonOmitKeys {
/**
* The last time the battery was persisted (in milliseconds since 1970)
*/
Expand All @@ -11,6 +12,8 @@ export class Battery {
private _lastLevel: number = -1;
private _levelCallbacks: Array<(action: BatteryLevelChangeAction) => void> = [];
private _lastChangeReportMs: number = 0;
/** @inheritDoc */
public readonly jsonOmitKeys: string[] = ['_device'];

public constructor(private readonly _device: iBatteryDevice) {}

Expand All @@ -34,10 +37,6 @@ export class Battery {
this._lastPersist = now;
}

public toJSON(): Partial<iBatteryDevice> {
return Utils.jsonFilter(this, ['_device']);
}

/**
* Checks whether the battery level did change and if so fires the callbacks
*/
Expand All @@ -64,4 +63,8 @@ export class Battery {
public addBatteryLevelCallback(pCallback: (action: BatteryLevelChangeAction) => void): void {
this._levelCallbacks.push(pCallback);
}

public toJSON(): Partial<iBatteryDevice> {
return Utils.jsonFilter(this, this.jsonOmitKeys);
}
}
13 changes: 8 additions & 5 deletions src/server/devices/sharedFunctions/handleSensor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import { iDisposable, LogDebugType, TelegramService, Utils, WeatherService } fro
import { HeatGroup, Window } from '../groups';
import { iHandleSensor } from '../baseDeviceInterfaces';
import { HandleSettings } from '../../../models/deviceSettings/handleSettings';
import { iJsonOmitKeys } from '../../../models/iJsonOmitKeys';

export class HandleSensor implements iDisposable {
export class HandleSensor implements iDisposable, iJsonOmitKeys {
/** @inheritDoc */
public readonly jsonOmitKeys: string[] = ['_device', 'window'];
/**
* The current position of the handle
*/
Expand Down Expand Up @@ -139,10 +142,6 @@ export class HandleSensor implements iDisposable {
this._closedCallback.push(pCallback);
}

public toJSON(): Partial<HandleSensor> {
return Utils.jsonFilter(this, ['_device', 'window']);
}

public dispose(): void {
if (this._iOpenTimeout) {
clearInterval(this._iOpenTimeout);
Expand All @@ -166,4 +165,8 @@ export class HandleSensor implements iDisposable {
public log(level: LogLevel, message: string, debugType: LogDebugType = LogDebugType.None): void {
this._device.log(level, message, debugType);
}

public toJSON(): Partial<HandleSensor> {
return Utils.jsonFilter(this, this.jsonOmitKeys);
}
}
13 changes: 8 additions & 5 deletions src/server/devices/sharedFunctions/humiditySensor.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Utils } from '../../services';
import { HumiditySensorChangeAction } from '../../../models';
import { iHumiditySensor, UNDEFINED_TEMP_VALUE } from '../baseDeviceInterfaces';
import { iJsonOmitKeys } from '../../../models/iJsonOmitKeys';

export class HumiditySensor {
export class HumiditySensor implements iJsonOmitKeys {
/** @inheritDoc */
public readonly jsonOmitKeys: string[] = ['_device'];
private _humidityCallbacks: ((action: HumiditySensorChangeAction) => void)[] = [];
private _humidity: number = UNDEFINED_TEMP_VALUE;
private readonly _persistHumiditySensorInterval: NodeJS.Timeout = Utils.guardedInterval(
Expand Down Expand Up @@ -37,14 +40,14 @@ export class HumiditySensor {
Utils.dbo?.persistHumiditySensor(this._device);
}

public toJSON(): Partial<HumiditySensor> {
return Utils.jsonFilter(this, ['_device']);
}

public addHumidityCallback(pCallback: (action: HumiditySensorChangeAction) => void): void {
this._humidityCallbacks.push(pCallback);
if (this._humidity > 0) {
pCallback(new HumiditySensorChangeAction(this._device, this._humidity));
}
}

public toJSON(): Partial<HumiditySensor> {
return Utils.jsonFilter(this, this.jsonOmitKeys);
}
}
7 changes: 5 additions & 2 deletions src/server/devices/sharedFunctions/temperatureSensor.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Utils } from '../../services';
import { TemperatureSensorChangeAction } from '../../../models';
import { iTemperatureSensor, UNDEFINED_TEMP_VALUE } from '../baseDeviceInterfaces';
import { iJsonOmitKeys } from '../../../models/iJsonOmitKeys';

export class TemperatureSensor {
export class TemperatureSensor implements iJsonOmitKeys {
/** @inheritDoc */
public readonly jsonOmitKeys: string[] = ['_device'];
/**
* The current room temperature as a number in Celsius
*/
Expand Down Expand Up @@ -55,6 +58,6 @@ export class TemperatureSensor {
}

public toJSON(): Partial<TemperatureSensor> {
return Utils.jsonFilter(this, ['_device']);
return Utils.jsonFilter(this, this.jsonOmitKeys);
}
}
6 changes: 5 additions & 1 deletion src/server/services/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { SettingsService } from '../settings-service';
import { CatchEmResult } from './catchEmResult';
import { iTimePair } from '../../config';
import { RGB } from './RGB';
import { iJsonOmitKeys } from '../../../models/iJsonOmitKeys';

export const DAYMS: number = 24 * 60 * 60 * 1000;

Expand Down Expand Up @@ -114,9 +115,11 @@ export class Utils {
'interval',
'timeouts',
'callback',
'callbacks',
'otaInfo',
'precalculatedDistancesMap',
'stateMap',
'jsonOmitKeys',
];
keysToOmit.push(...additionalOmitKeys);
const loweredOmitKeys: string[] = keysToOmit.map((key) => key.toLowerCase());
Expand Down Expand Up @@ -223,14 +226,15 @@ export class Utils {
if (level > 10 && level < 20) {
ServerLogService.writeLog(LogLevel.Warn, `DeepOmit Loop Level ${level} reached for ${currentKey}`);
}
const combinedOmmitKeys: string[] = [...keysToOmit, ...((obj as iJsonOmitKeys)?.jsonOmitKeys ?? [])];
// the inner function which will be called recursivley
return _.transform(obj, (result: { [name: string]: unknown }, value, key: string | number) => {
if (value === undefined || value === null) {
return;
}
if (typeof key == 'string') {
const lowerKey: string = key.toLowerCase();
for (const checkKey of keysToOmit) {
for (const checkKey of combinedOmmitKeys) {
// if the key is in the index skip it
if (lowerKey.includes(checkKey)) {
return;
Expand Down
8 changes: 5 additions & 3 deletions src/server/services/victron/victron-device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import {
iExcessEnergyConsumer,
} from '../../devices';
import { EnergyConsumerStateChange, EnergyManagerUtils, Utils } from '../utils';
import { EnergyCalculation, LogLevel, TimeOfDay, VictronDeviceSettings } from '../../../models';
import { EnergyCalculation, iJsonOmitKeys, LogLevel, TimeOfDay, VictronDeviceSettings } from '../../../models';
import { LogDebugType, ServerLogService } from '../log-service';
import { VictronDeviceData, VictronMqttConnectionOptions, VictronMqttConsumer } from 'victron-mqtt-consumer';
import { SunTimeOffsets, TimeCallbackService } from '../time-callback-service';

export class VictronDevice implements iEnergyManager, iBatteryDevice {
export class VictronDevice implements iEnergyManager, iBatteryDevice, iJsonOmitKeys {
/** @inheritDoc */
public readonly jsonOmitKeys: string[] = ['_victronConsumer', '_excessEnergyConsumer'];
/** @inheritDoc */
public readonly deviceCapabilities: DeviceCapability[] = [
DeviceCapability.energyManager,
Expand Down Expand Up @@ -200,7 +202,7 @@ export class VictronDevice implements iEnergyManager, iBatteryDevice {
injectingWattage: this.injectingWattage,
selfConsumingWattage: this.selfConsumingWattage,
},
...Utils.jsonFilter(this, ['_victronConsumer', '_excessEnergyConsumer']),
...Utils.jsonFilter(this, this.jsonOmitKeys),
};
}

Expand Down

0 comments on commit 732fe7e

Please sign in to comment.