Why Typed Value is used in Mulesoft?

Kritika gupta
2 min readOct 27, 2020

--

Mulesoft has the concept of Typed Value.
Typed Value represents the data-type of object which comprises of data itself and its associated MIME type (i.e. application/json, application/xml etc.).

I am defining two use case here -

  1. When consuming payload — As per documentation of Mulesoft ,

A common use case for Operations and Sources is to receive Media Type information along with the value of the parameter.” for example:

Example: Operation

public void receiveContent(InputStream content) {
// operation logic
}

Here, receiveContent is an operation and content is its parameter which is of InputStream type.
This content must be a payload &
All variables, payload are TypedValue that means all payload contains MIME type within it.
Here, is how we can access it in operation —
It is also called Media-Type-Friendly Parameter

public void receiveContent(TypedValue<InputStream> content) {
DataType dataType = content.getDataType();
MediaType mediaType = dataType.getMediaType();
boolean streamType = dataType.isStreamType();
Long lenght = content.getLength().orElse(-1L);
InputStream theContent = content.value(); // The proper value System.out.println(mediaType); // application/json; UTF-8
System.out.println(streamType); // true
System.out.println(lenght); // 18
}

2. When creating payload — It is used when creating any custom connector or equivalent using Mule SDK. This is common usecase when the operation is returning something and that must be payload.

Since, payload is a typed value- We need to wrap our content with media-type(MIME type) information as well.

InputStream content = new TypedValue<>(content, DataType.builder().type(InputStream.class).mediaType("application/json").build());

Here, the operation in which we create payload to return,will contain media-type information too along with content.

Why it is used?
All the payloads in the mule app is subject to transform using MuleSoft Expression Language — DataWeave. Since, DataWeave can read and write many types of data formats.

So, have you ever think, how dataweave infer the type of input so that it can set-up reader for that type?

Example — How dataweave understands that it is going to read json or xml or any other type?
Yes, you guess it right. The answer is the media-type information attached to payload.All this happens, under the hood but the common and important reason behind attaching media-type information with payload is to make it a type which dataweave can infer and read the content correctly.

--

--

Kritika gupta
Kritika gupta

Written by Kritika gupta

Fertile minded Web Application Developer . Love to explore JavaScript,Angular,Java and looking to increase work productivity. Developer @ Xoriant Solutions

Responses (1)