使用 Dataweave Mule 从电话号码中查找国家/地区代码

Inf*_*ity 3 mule dataweave

我的输入请求 JSON 如下所示:

{
    "phoneNumbers": [{
        "phoneNumberType": "mobile",
        "phoneNumber": "54112724555"
    },
    {
        "phoneNumberType": "mobile",
        "phoneNumber": "16298765432"
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我想像这样生成输出 Json:

{
    "phoneNumbers": [{
        "phoneNumberType": "mobile",
        "phoneNumber": "54112724555",
        "CountryCode": "ARG"
    },
    {
        "phoneNumberType": "mobile",
        "phoneNumber": "16298765432",
        "CountryCode": "US"
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我使用 csv 文件中给出的 callCode 和 CountryCode Mapping 从 PhoneNumber 派生 countryCode。

CALLING_CODE,COUNTRY_CODE
1,US
7,RU
54,AR
20,EG
32,BE
33,FR
505,NI
506,CR
1876,JM
1905,CA
1939,PR
262262,RE
262269,YT
.,.
.,.
Run Code Online (Sandbox Code Playgroud)

我使用 fileConnector 读取 CSV 文件并将其存储在 Vars.CallingCodeMapping 中。

我必须通过从匹配返回 countryCode 的电话号码中传递第一个字母然后传递前两个字母 ....firstsixLetter 如果没有匹配返回 NA 来使用呼叫代码查找电话号码。

mac*_*val 5

将此输入作为有效载荷

[
   "54112724555",
   "16298765432"
]
Run Code Online (Sandbox Code Playgroud)

这个 csv 在一个叫做country_codes的 var 中

%dw 2.0
output application/json

var codeByCode = vars.country_code groupBy ((item, index) -> item.CALLING_CODE)
/**
* Returns the Country code or Null if not found
*/
fun lookupCountrCode(phoneNumber:String): String | Null = 
    //map the each sub part to a country code or null
    (0 to 6 map ((index) ->  codeByCode[phoneNumber[0 to index]]) 
            //Filter non null and take the first this will return null if array is empty
            filter ((item, index) -> item != null))[0]

---
payload map ((item, index) -> lookupCountrCode(item))
Run Code Online (Sandbox Code Playgroud)

输出

[
  [
    {
      "CALLING_CODE": "54",
      "COUNTRY_CODE": "ARG"
    }
  ],
  [
    {
      "CALLING_CODE": "1",
      "COUNTRY_CODE": "US"
    }
  ]
]
Run Code Online (Sandbox Code Playgroud)