Skip to content

Commit f51a85b

Browse files
committed
feat: Add TypeMapper interface
1 parent 2a6cd23 commit f51a85b

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.retailsvc.http;
2+
3+
/**
4+
* Reads and writes request/response bodies for a specific media type. Registered on {@link
5+
* OpenApiServer.Builder#bodyMapper(String, TypeMapper)} keyed by media type. The library ships
6+
* built-in mappers for {@code application/x-www-form-urlencoded} and {@code text/plain}; an {@code
7+
* application/json} mapper must be supplied by the caller or auto-detected via Gson on the
8+
* classpath.
9+
*/
10+
public interface TypeMapper {
11+
12+
/**
13+
* @param body raw request body bytes
14+
* @param contentTypeHeader the full raw {@code Content-Type} header, used for charset and other
15+
* parameters (the JSON mapper ignores it)
16+
*/
17+
Object readFrom(byte[] body, String contentTypeHeader);
18+
19+
/** Serializes {@code value} to bytes suitable for writing as the response body. */
20+
byte[] writeTo(Object value);
21+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.retailsvc.http;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import java.nio.charset.StandardCharsets;
6+
import org.junit.jupiter.api.Test;
7+
8+
class TypeMapperShapeTest {
9+
10+
@Test
11+
void roundTripsViaInlineImplementation() {
12+
TypeMapper identity =
13+
new TypeMapper() {
14+
@Override
15+
public Object readFrom(byte[] body, String contentTypeHeader) {
16+
return new String(body, StandardCharsets.UTF_8);
17+
}
18+
19+
@Override
20+
public byte[] writeTo(Object value) {
21+
return ((String) value).getBytes(StandardCharsets.UTF_8);
22+
}
23+
};
24+
25+
Object read = identity.readFrom("hi".getBytes(StandardCharsets.UTF_8), "text/plain");
26+
assertThat(read).isEqualTo("hi");
27+
assertThat(identity.writeTo("hi")).containsExactly('h', 'i');
28+
}
29+
}

0 commit comments

Comments
 (0)