【发布时间】:2016-05-24 17:39:57
【问题描述】:
在我的应用程序中,一些查询参数是可选的。 我将这些查询参数存储在变量中。
我想使用这些变量通过 DataWeave 过滤对象。 如果没有传入查询参数并且变量为空或不存在,则需要返回所有对象,因此无需过滤。
让我们以传入的能量类型参数为例。 存储在流变量中:energytypeVar(值可能是“gas”、“electricity”、“water”)
过滤器应用于底部的对象: 过滤器 $.attributes.energyType == flowVars.energytypeVar
我尝试了各种使用条件逻辑何时/否则仅在提供实际值时进行过滤的方法。 否则我根本不希望执行过滤器,因此返回所有对象。 当变量没有有效的“energyType”时,完整的数据对象为空。
DW 脚本
%dw 1.0
%output application/json
%var resourceUrl="https://hostname/devices"
%var collectionSize = sizeOf payload.Envelope.Body.GetEnergyDevicesResponse.GetEnergyDevicesResult
---
{
meta:{code: 200, timestamp: now},
data: payload.Envelope.Body.GetEnergyDevicesResponse.GetEnergyDevicesResult map {
type: "device",
id: $.EnergyDeviceId,
attributes: {
energyType: $.EnergyType,
deviceModel: $.HWModel,
serialNumber: $.SerialNumber,
name: $.Name,
applianceType: $.applianceType,
isCentralMeter: $.IsCentralMeter as :boolean,
isSwitchable: $.IsSwitchable as :boolean,
isOnline: $.IsOnline as :boolean,
isProducer: $.IsProducer as :boolean,
isSwitchedOn: $.IsSwitchedOn as :boolean,
isLiveUsageEnabled: $.IsLiveUsageEnabled as :boolean,
index: {
value: $.MeterIndexValue,
unit: 'm3' unless $.EnergyType == "electricity" otherwise "Wh",
timestamp: $.MeterIndexTimestamp
} when ($.IsCentralMeter == "true") otherwise null
},
links: {
self: resourceUrl ++ '/' ++ $.EnergyDeviceId
}
} filter $.attributes.energyType == flowVars.energytypeVar
}
回答后的解决方案 (应用了额外的过滤)
%dw 1.0
%output application/json
%var resourceUrl="https://hostname/devices"
%var collectionSize = sizeOf payload.Envelope.Body.GetEnergyDevicesResponse.GetEnergyDevicesResult
---
using (result = payload.Envelope.Body.GetEnergyDevicesResponse.GetEnergyDevicesResult map {
type: "device",
id: $.EnergyDeviceId,
attributes: {
energyType: $.EnergyType,
deviceModel: $.HWModel,
serialNumber: $.SerialNumber,
name: $.Name,
applianceType: $.applianceType,
isCentralMeter: $.IsCentralMeter as :boolean,
isSwitchable: $.IsSwitchable as :boolean,
isOnline: $.IsOnline as :boolean,
isProducer: $.IsProducer as :boolean,
isSwitchedOn: $.IsSwitchedOn as :boolean,
isLiveUsageEnabled: $.IsLiveUsageEnabled as :boolean,
index: {
value: $.MeterIndexValue,
unit: 'm3' unless $.EnergyType == "electricity" otherwise "Wh",
timestamp: $.MeterIndexTimestamp
} when ($.IsCentralMeter == "true") otherwise null
},
links: {
self: resourceUrl ++ '/' ++ $.EnergyDeviceId
}
})
{
meta:{code: 200, timestamp: now},
data: result filter ($.id == flowVars.deviceId) when (flowVars.deviceId != 0) otherwise {
data: result filter ($.attributes.energyType == flowVars.energyType) when flowVars.energyType != 0
otherwise result
} distinctBy $.data
}
【问题讨论】:
标签: mule mule-studio dataweave