修改字符串字段内容的MuleSoft转换消息



如何修改下面的MuleSoft转换消息以反转EMPLOYEE_CODE字段的串联?

背景:我正在使用一个MuleSoft进程,该进程(I(使用"SELECT"组件从数据库中查询数据;(ii(然后使用一系列"Transform Message"组件将其转换为指定的.csv格式;(iii(将.csv存储到SFTP服务器上。

其中一个数据字段(EMPLOYEE_CODE(具有来自DB的数据,其格式为:01-1111("-"前两个字符,"-"后四个字符(。我需要我的MuleSoft Transform消息来交换EMPLOYEE_CODE字段中的分隔顺序,以便在生成.csv文件之前以这种格式输出它:1111-01(后四个字符现在在"-"之前,前两个字符在"-"之后(。

当前MuleSoft转换消息:

%dw 2.0
output application/csv
quoteValues=true
---
payload map {
employeeID: $.EMPL_ID,
firstName: $.FIRST_NAME,
lastName: $.LAST_NAME,
employeeCode: $.EMPLOYEE_CODE
}

作为参考,这里有一个我从DB:收到的示例数据表

EMPLOYEE_CODE史密斯
EMPL_IDFIRST_NAMELAST_NAME
0000001JohnDoe01-1111
0000002里克詹姆斯02-2222
0000003约翰03-3333

看起来你只需要用一个非常基本的字符串操作来更新字段EMPLOYEE_CODE(以不同的顺序连接子字符串(。我使用了更新操作符来解决在脚本之前转换数据的问题。其他字段与此解决方案无关。

%dw 2.0
output application/java
---
payload map (
$ update {
case code at .EMPLOYEE_CODE -> code[3 to -1] ++ "-" ++ code[0 to 1]
}
)

如果你喜欢与你的脚本集成,只需替换这一行:

employeeCode: $.EMPLOYEE_CODE[3 to -1] ++ "-" ++ $.EMPLOYEE_CODE[0 to 1]

另一种内置字符串函数的方法:

%dw 2.0
import * from dw::core::Strings
output application/json
var inp = "01-1111"
---
substringAfter(inp,"-")++"-"++ substringBefore(inp,"-")

使用纯字符串操作的替代方法

%dw 2.0
import * from dw::core::Strings
output application/json
var inp = "01-1111"
---
rightPad(rightPad(substringAfter(inp,"-"),5,"-"),6,substringBefore(inp,"-"))

在任何一种情况下,您都可以将inp替换为$.EEMPLOYEE_CODE

一种更通用的方法:

StringUtils.dwl:

%dw 2.0
/**
* Reverse the tokens position of a delimited string.
*
* === Parameters
*
* [%header, cols="1,13"]
* |===
* | Name | Type | Description
* | `delimitedString` | `String | Null` | An optional string that contains a delimiter.
* | `delimiter` | `String` | The delimiter.
* |===
*
* === Example
*
* This example reverse the string "01-1111" into "1111-01"
*
* ==== Source
*
* [source,DataWeave,linenums]
* ----
* %dw 2.0
* output application/json
* ---
* reverseTokens("01-1111", "-")
* ----
*
* ==== Output
*
* `Expression Output`
*
* [source,XML,linenums]
* ----
* "1111-01"
* ----
*/
fun reverseTokens(delimitedString : String | Null, delimiter : String) = do {
var tokens = (delimitedString splitBy delimiter ) default []
---
tokens[-1 to 0] joinBy delimiter
}

main.dwl:

%dw 2.0
output application/csv quoteValues=true
import StringUtils
---
payload map {
employeeID: $.EMPL_ID,
firstName: $.FIRST_NAME,
lastName: $.LAST_NAME,
employeeCode: StringUtils::reverseTokens($.EMPLOYEE_CODE, '-')
}

最新更新