How add values in JSON to get a cumulative total using Dataweave

Viewed 40

I have a json object that has the memory, cpu and number of replicas for each API in the system.

I need to calculate the total CPU and Memory where the CPU / Memory for each API is cpu * number fo replicas. Take a look at the following input JSON

var payload = [
    {
        "id": "5a9b06b3-ed2c-4382-cf41427b6f56",
        "name": "api-1",
        "cpuReserved": 0.2,
        "cpuLimit": 0.5,
        "memReserved": 2,
        "memLimit": 2,
        "replicas": 1,
        "status": "RUNNING"
    },
    {
        "id": "79a90d5e-d042-9a6c-61cbe1341d04",
        "name": "api-2",
        "cpuReserved": 0.2,
        "cpuLimit": 1,
        "memReserved": 2,
        "memLimit": 2,
        "replicas": 2,
        "status": "RUNNING"
    },
    {
        "id": "15d0e51f-198c-948c-c4c864a5dd72",
        "name": "api-3",
        "cpuReserved": 0.2,
        "cpuLimit": 0.5,
        "memReserved": 2,
        "memLimit": 2,
        "replicas": 1,
        "status": "RUNNING"
    }
]

The output required is something like this:

"report": {
      "count": 3,
      "totalCPULimit": 3,
      "totalCPUReserved": 0.8,
      "totalMemReserved": 8,
      "totalMemLimit": 8
    }

Note: out of the 3 APIS in the input; 1 API has 2 replicas while the other 2 APIs have 1 replica each.

How can I generate this output using Dataweave in MuleSoft 4?

2 Answers

Pretty crude though it can get you to the desired:

%dw 2.0
output application/json
var totals = payload map {
      a: $.cpuLimit * $.replicas,
      b: $.cpuReserved * $.replicas,
      c: $.memReserved * $.replicas,
      d: $.memLimit *$.replicas
}

---
"report": {
      "count": sizeOf(payload),
      "totalCPULimit": sum(totals.a),
      "totalCPUReserved": sum(totals.b),
      "totalMemReserved": sum(totals.c),
      "totalMemLimit": sum(totals.d),
    }

I found another way of doing it deriving from an XML transformation code

%dw 2.0
output application/json

---
    "report": {
      "count": sizeOf(payload) as String,
      "totalCPULimit": sum(payload map($.cpuLimit * $.replicas)),
      "totalCPUReserved": sum(payload map($.cpuReserved * $.replicas)),
      "totalMemReserved": sum(payload map($.memReserved * $.replicas)),
      "totalMemLimit": sum(payload map($.memLimit * $.replicas)),
    } 
]

Related