JSON, routing & embedding

You can find all the code for this chapter here

In the previous chapter we created a web server to store how many games players have won.

Our product owner has a new requirement; to have a new endpoint called /league which returns a list of all players stored. She would like this to be returned as JSON.

Here is the code we have so far

  1. // server.go
  2. package main
  3. import (
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. )
  8. type PlayerStore interface {
  9. GetPlayerScore(name string) int
  10. RecordWin(name string)
  11. }
  12. type PlayerServer struct {
  13. store PlayerStore
  14. }
  15. func (p *PlayerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  16. player := strings.TrimPrefix(r.URL.Path, "/players/")
  17. switch r.Method {
  18. case http.MethodPost:
  19. p.processWin(w, player)
  20. case http.MethodGet:
  21. p.showScore(w, player)
  22. }
  23. }
  24. func (p *PlayerServer) showScore(w http.ResponseWriter, player string) {
  25. score := p.store.GetPlayerScore(player)
  26. if score == 0 {
  27. w.WriteHeader(http.StatusNotFound)
  28. }
  29. fmt.Fprint(w, score)
  30. }
  31. func (p *PlayerServer) processWin(w http.ResponseWriter, player string) {
  32. p.store.RecordWin(player)
  33. w.WriteHeader(http.StatusAccepted)
  34. }
  1. // in_memory_player_store.go
  2. package main
  3. func NewInMemoryPlayerStore() *InMemoryPlayerStore {
  4. return &InMemoryPlayerStore{map[string]int{}}
  5. }
  6. type InMemoryPlayerStore struct {
  7. store map[string]int
  8. }
  9. func (i *InMemoryPlayerStore) RecordWin(name string) {
  10. i.store[name]++
  11. }
  12. func (i *InMemoryPlayerStore) GetPlayerScore(name string) int {
  13. return i.store[name]
  14. }
  1. // main.go
  2. package main
  3. import (
  4. "log"
  5. "net/http"
  6. )
  7. func main() {
  8. server := &PlayerServer{NewInMemoryPlayerStore()}
  9. log.Fatal(http.ListenAndServe(":5000", server))
  10. }

You can find the corresponding tests in the link at the top of the chapter.

We’ll start by making the league table endpoint.

Write the test first

We’ll extend the existing suite as we have some useful test functions and a fake PlayerStore to use.

  1. //server_test.go
  2. func TestLeague(t *testing.T) {
  3. store := StubPlayerStore{}
  4. server := &PlayerServer{&store}
  5. t.Run("it returns 200 on /league", func(t *testing.T) {
  6. request, _ := http.NewRequest(http.MethodGet, "/league", nil)
  7. response := httptest.NewRecorder()
  8. server.ServeHTTP(response, request)
  9. assertStatus(t, response.Code, http.StatusOK)
  10. })
  11. }

Before worrying about actual scores and JSON we will try and keep the changes small with the plan to iterate toward our goal. The simplest start is to check we can hit /league and get an OK back.

Try to run the test

  1. --- FAIL: TestLeague/it_returns_200_on_/league (0.00s)
  2. server_test.go:101: status code is wrong: got 404, want 200
  3. FAIL
  4. FAIL playerstore 0.221s
  5. FAIL

Our PlayerServer returns a 404 Not Found, as if we were trying to get the wins for an unknown player. Looking at how server.go implements ServeHTTP, we realize that it always assumes to be called with a URL pointing to a specific player:

  1. player := strings.TrimPrefix(r.URL.Path, "/players/")

In the previous chapter, we mentioned this was a fairly naive way of doing our routing. Our test informs us correctly that we need a concept how to deal with different request paths.

Write enough code to make it pass

Go has a built-in routing mechanism called ServeMux (request multiplexer) which lets you attach http.Handlers to particular request paths.

Let’s commit some sins and get the tests passing in the quickest way we can, knowing we can refactor it with safety once we know the tests are passing.

  1. //server.go
  2. func (p *PlayerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  3. router := http.NewServeMux()
  4. router.Handle("/league", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  5. w.WriteHeader(http.StatusOK)
  6. }))
  7. router.Handle("/players/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  8. player := strings.TrimPrefix(r.URL.Path, "/players/")
  9. switch r.Method {
  10. case http.MethodPost:
  11. p.processWin(w, player)
  12. case http.MethodGet:
  13. p.showScore(w, player)
  14. }
  15. }))
  16. router.ServeHTTP(w, r)
  17. }
  • When the request starts we create a router and then we tell it for x path use y handler.
  • So for our new endpoint, we use http.HandlerFunc and an anonymous function to w.WriteHeader(http.StatusOK) when /league is requested to make our new test pass.
  • For the /players/ route we just cut and paste our code into another http.HandlerFunc.
  • Finally, we handle the request that came in by calling our new router’s ServeHTTP (notice how ServeMux is also an http.Handler?)

The tests should now pass.

Refactor

ServeHTTP is looking quite big, we can separate things out a bit by refactoring our handlers into separate methods.

  1. //server.go
  2. func (p *PlayerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  3. router := http.NewServeMux()
  4. router.Handle("/league", http.HandlerFunc(p.leagueHandler))
  5. router.Handle("/players/", http.HandlerFunc(p.playersHandler))
  6. router.ServeHTTP(w, r)
  7. }
  8. func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
  9. w.WriteHeader(http.StatusOK)
  10. }
  11. func (p *PlayerServer) playersHandler(w http.ResponseWriter, r *http.Request) {
  12. player := strings.TrimPrefix(r.URL.Path, "/players/")
  13. switch r.Method {
  14. case http.MethodPost:
  15. p.processWin(w, player)
  16. case http.MethodGet:
  17. p.showScore(w, player)
  18. }
  19. }

It’s quite odd (and inefficient) to be setting up a router as a request comes in and then calling it. What we ideally want to do is have some kind of NewPlayerServer function which will take our dependencies and do the one-time setup of creating the router. Each request can then just use that one instance of the router.

  1. //server.go
  2. type PlayerServer struct {
  3. store PlayerStore
  4. router *http.ServeMux
  5. }
  6. func NewPlayerServer(store PlayerStore) *PlayerServer {
  7. p := &PlayerServer{
  8. store,
  9. http.NewServeMux(),
  10. }
  11. p.router.Handle("/league", http.HandlerFunc(p.leagueHandler))
  12. p.router.Handle("/players/", http.HandlerFunc(p.playersHandler))
  13. return p
  14. }
  15. func (p *PlayerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  16. p.router.ServeHTTP(w, r)
  17. }
  • PlayerServer now needs to store a router.
  • We have moved the routing creation out of ServeHTTP and into our NewPlayerServer so this only has to be done once, not per request.
  • You will need to update all the test and production code where we used to do PlayerServer{&store} with NewPlayerServer(&store).

One final refactor

Try changing the code to the following.

  1. type PlayerServer struct {
  2. store PlayerStore
  3. http.Handler
  4. }
  5. func NewPlayerServer(store PlayerStore) *PlayerServer {
  6. p := new(PlayerServer)
  7. p.store = store
  8. router := http.NewServeMux()
  9. router.Handle("/league", http.HandlerFunc(p.leagueHandler))
  10. router.Handle("/players/", http.HandlerFunc(p.playersHandler))
  11. p.Handler = router
  12. return p
  13. }

Then replace server := &PlayerServer{&store} with server := NewPlayerServer(&store) in server_test.go, server_integration_test.go, and main.go.

Finally make sure you delete func (p *PlayerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) as it is no longer needed!

Embedding

We changed the second property of PlayerServer, removing the named property router http.ServeMux and replaced it with http.Handler; this is called embedding.

Go does not provide the typical, type-driven notion of subclassing, but it does have the ability to “borrow” pieces of an implementation by embedding types within a struct or interface.

Effective Go - Embedding

What this means is that our PlayerServer now has all the methods that http.Handler has, which is just ServeHTTP.

To “fill in” the http.Handler we assign it to the router we create in NewPlayerServer. We can do this because http.ServeMux has the method ServeHTTP.

This lets us remove our own ServeHTTP method, as we are already exposing one via the embedded type.

Embedding is a very interesting language feature. You can use it with interfaces to compose new interfaces.

  1. type Animal interface {
  2. Eater
  3. Sleeper
  4. }

And you can use it with concrete types too, not just interfaces. As you’d expect if you embed a concrete type you’ll have access to all its public methods and fields.

Any downsides?

You must be careful with embedding types because you will expose all public methods and fields of the type you embed. In our case, it is ok because we embedded just the interface that we wanted to expose (http.Handler).

If we had been lazy and embedded http.ServeMux instead (the concrete type) it would still work but users of PlayerServer would be able to add new routes to our server because Handle(path, handler) would be public.

When embedding types, really think about what impact that has on your public API.

It is a very common mistake to misuse embedding and end up polluting your APIs and exposing the internals of your type.

Now we’ve restructured our application we can easily add new routes and have the start of the /league endpoint. We now need to make it return some useful information.

We should return some JSON that looks something like this.

  1. [
  2. {
  3. "Name":"Bill",
  4. "Wins":10
  5. },
  6. {
  7. "Name":"Alice",
  8. "Wins":15
  9. }
  10. ]

Write the test first

We’ll start by trying to parse the response into something meaningful.

  1. //server_test.go
  2. func TestLeague(t *testing.T) {
  3. store := StubPlayerStore{}
  4. server := NewPlayerServer(&store)
  5. t.Run("it returns 200 on /league", func(t *testing.T) {
  6. request, _ := http.NewRequest(http.MethodGet, "/league", nil)
  7. response := httptest.NewRecorder()
  8. server.ServeHTTP(response, request)
  9. var got []Player
  10. err := json.NewDecoder(response.Body).Decode(&got)
  11. if err != nil {
  12. t.Fatalf("Unable to parse response from server %q into slice of Player, '%v'", response.Body, err)
  13. }
  14. assertStatus(t, response.Code, http.StatusOK)
  15. })
  16. }

Why not test the JSON string?

You could argue a simpler initial step would be just to assert that the response body has a particular JSON string.

In my experience tests that assert against JSON strings have the following problems.

  • Brittleness. If you change the data-model your tests will fail.
  • Hard to debug. It can be tricky to understand what the actual problem is when comparing two JSON strings.
  • Poor intention. Whilst the output should be JSON, what’s really important is exactly what the data is, rather than how it’s encoded.
  • Re-testing the standard library. There is no need to test how the standard library outputs JSON, it is already tested. Don’t test other people’s code.

Instead, we should look to parse the JSON into data structures that are relevant for us to test with.

Data modelling

Given the JSON data model, it looks like we need an array of Player with some fields so we have created a new type to capture this.

  1. //server.go
  2. type Player struct {
  3. Name string
  4. Wins int
  5. }

JSON decoding

  1. //server_test.go
  2. var got []Player
  3. err := json.NewDecoder(response.Body).Decode(&got)

To parse JSON into our data model we create a Decoder from encoding/json package and then call its Decode method. To create a Decoder it needs an io.Reader to read from which in our case is our response spy’s Body.

Decode takes the address of the thing we are trying to decode into which is why we declare an empty slice of Player the line before.

Parsing JSON can fail so Decode can return an error. There’s no point continuing the test if that fails so we check for the error and stop the test with t.Fatalf if it happens. Notice that we print the response body along with the error as it’s important for someone running the test to see what string cannot be parsed.

Try to run the test

  1. === RUN TestLeague/it_returns_200_on_/league
  2. --- FAIL: TestLeague/it_returns_200_on_/league (0.00s)
  3. server_test.go:107: Unable to parse response from server '' into slice of Player, 'unexpected end of JSON input'

Our endpoint currently does not return a body so it cannot be parsed into JSON.

Write enough code to make it pass

  1. //server.go
  2. func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
  3. leagueTable := []Player{
  4. {"Chris", 20},
  5. }
  6. json.NewEncoder(w).Encode(leagueTable)
  7. w.WriteHeader(http.StatusOK)
  8. }

The test now passes.

Encoding and Decoding

Notice the lovely symmetry in the standard library.

  • To create an Encoder you need an io.Writer which is what http.ResponseWriter implements.
  • To create a Decoder you need an io.Reader which the Body field of our response spy implements.

Throughout this book, we have used io.Writer and this is another demonstration of its prevalence in the standard library and how a lot of libraries easily work with it.

Refactor

It would be nice to introduce a separation of concern between our handler and getting the leagueTable as we know we’re going to not hard-code that very soon.

  1. //server.go
  2. func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
  3. json.NewEncoder(w).Encode(p.getLeagueTable())
  4. w.WriteHeader(http.StatusOK)
  5. }
  6. func (p *PlayerServer) getLeagueTable() []Player {
  7. return []Player{
  8. {"Chris", 20},
  9. }
  10. }

Next, we’ll want to extend our test so that we can control exactly what data we want back.

Write the test first

We can update the test to assert that the league table contains some players that we will stub in our store.

Update StubPlayerStore to let it store a league, which is just a slice of Player. We’ll store our expected data in there.

  1. //server_test.go
  2. type StubPlayerStore struct {
  3. scores map[string]int
  4. winCalls []string
  5. league []Player
  6. }

Next, update our current test by putting some players in the league property of our stub and assert they get returned from our server.

  1. //server_test.go
  2. func TestLeague(t *testing.T) {
  3. t.Run("it returns the league table as JSON", func(t *testing.T) {
  4. wantedLeague := []Player{
  5. {"Cleo", 32},
  6. {"Chris", 20},
  7. {"Tiest", 14},
  8. }
  9. store := StubPlayerStore{nil, nil, wantedLeague}
  10. server := NewPlayerServer(&store)
  11. request, _ := http.NewRequest(http.MethodGet, "/league", nil)
  12. response := httptest.NewRecorder()
  13. server.ServeHTTP(response, request)
  14. var got []Player
  15. err := json.NewDecoder(response.Body).Decode(&got)
  16. if err != nil {
  17. t.Fatalf("Unable to parse response from server %q into slice of Player, '%v'", response.Body, err)
  18. }
  19. assertStatus(t, response.Code, http.StatusOK)
  20. if !reflect.DeepEqual(got, wantedLeague) {
  21. t.Errorf("got %v want %v", got, wantedLeague)
  22. }
  23. })
  24. }

Try to run the test

  1. ./server_test.go:33:3: too few values in struct initializer
  2. ./server_test.go:70:3: too few values in struct initializer

Write the minimal amount of code for the test to run and check the failing test output

You’ll need to update the other tests as we have a new field in StubPlayerStore; set it to nil for the other tests.

Try running the tests again and you should get

  1. === RUN TestLeague/it_returns_the_league_table_as_JSON
  2. --- FAIL: TestLeague/it_returns_the_league_table_as_JSON (0.00s)
  3. server_test.go:124: got [{Chris 20}] want [{Cleo 32} {Chris 20} {Tiest 14}]

Write enough code to make it pass

We know the data is in our StubPlayerStore and we’ve abstracted that away into an interface PlayerStore. We need to update this so anyone passing us in a PlayerStore can provide us with the data for leagues.

  1. //server.go
  2. type PlayerStore interface {
  3. GetPlayerScore(name string) int
  4. RecordWin(name string)
  5. GetLeague() []Player
  6. }

Now we can update our handler code to call that rather than returning a hard-coded list. Delete our method getLeagueTable() and then update leagueHandler to call GetLeague().

  1. //server.go
  2. func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
  3. json.NewEncoder(w).Encode(p.store.GetLeague())
  4. w.WriteHeader(http.StatusOK)
  5. }

Try and run the tests.

  1. # github.com/quii/learn-go-with-tests/json-and-io/v4
  2. ./main.go:9:50: cannot use NewInMemoryPlayerStore() (type *InMemoryPlayerStore) as type PlayerStore in argument to NewPlayerServer:
  3. *InMemoryPlayerStore does not implement PlayerStore (missing GetLeague method)
  4. ./server_integration_test.go:11:27: cannot use store (type *InMemoryPlayerStore) as type PlayerStore in argument to NewPlayerServer:
  5. *InMemoryPlayerStore does not implement PlayerStore (missing GetLeague method)
  6. ./server_test.go:36:28: cannot use &store (type *StubPlayerStore) as type PlayerStore in argument to NewPlayerServer:
  7. *StubPlayerStore does not implement PlayerStore (missing GetLeague method)
  8. ./server_test.go:74:28: cannot use &store (type *StubPlayerStore) as type PlayerStore in argument to NewPlayerServer:
  9. *StubPlayerStore does not implement PlayerStore (missing GetLeague method)
  10. ./server_test.go:106:29: cannot use &store (type *StubPlayerStore) as type PlayerStore in argument to NewPlayerServer:
  11. *StubPlayerStore does not implement PlayerStore (missing GetLeague method)

The compiler is complaining because InMemoryPlayerStore and StubPlayerStore do not have the new method we added to our interface.

For StubPlayerStore it’s pretty easy, just return the league field we added earlier.

  1. //server_test.go
  2. func (s *StubPlayerStore) GetLeague() []Player {
  3. return s.league
  4. }

Here’s a reminder of how InMemoryStore is implemented.

  1. //in_memory_player_store.go
  2. type InMemoryPlayerStore struct {
  3. store map[string]int
  4. }

Whilst it would be pretty straightforward to implement GetLeague “properly” by iterating over the map remember we are just trying to write the minimal amount of code to make the tests pass.

So let’s just get the compiler happy for now and live with the uncomfortable feeling of an incomplete implementation in our InMemoryStore.

  1. //in_memory_player_store.go
  2. func (i *InMemoryPlayerStore) GetLeague() []Player {
  3. return nil
  4. }

What this is really telling us is that later we’re going to want to test this but let’s park that for now.

Try and run the tests, the compiler should pass and the tests should be passing!

Refactor

The test code does not convey our intent very well and has a lot of boilerplate we can refactor away.

  1. //server_test.go
  2. t.Run("it returns the league table as JSON", func(t *testing.T) {
  3. wantedLeague := []Player{
  4. {"Cleo", 32},
  5. {"Chris", 20},
  6. {"Tiest", 14},
  7. }
  8. store := StubPlayerStore{nil, nil, wantedLeague}
  9. server := NewPlayerServer(&store)
  10. request := newLeagueRequest()
  11. response := httptest.NewRecorder()
  12. server.ServeHTTP(response, request)
  13. got := getLeagueFromResponse(t, response.Body)
  14. assertStatus(t, response.Code, http.StatusOK)
  15. assertLeague(t, got, wantedLeague)
  16. })

Here are the new helpers

  1. //server_test.go
  2. func getLeagueFromResponse(t testing.TB, body io.Reader) (league []Player) {
  3. t.Helper()
  4. err := json.NewDecoder(body).Decode(&league)
  5. if err != nil {
  6. t.Fatalf("Unable to parse response from server %q into slice of Player, '%v'", body, err)
  7. }
  8. return
  9. }
  10. func assertLeague(t testing.TB, got, want []Player) {
  11. t.Helper()
  12. if !reflect.DeepEqual(got, want) {
  13. t.Errorf("got %v want %v", got, want)
  14. }
  15. }
  16. func newLeagueRequest() *http.Request {
  17. req, _ := http.NewRequest(http.MethodGet, "/league", nil)
  18. return req
  19. }

One final thing we need to do for our server to work is make sure we return a content-type header in the response so machines can recognise we are returning JSON.

Write the test first

Add this assertion to the existing test

  1. //server_test.go
  2. if response.Result().Header.Get("content-type") != "application/json" {
  3. t.Errorf("response did not have content-type of application/json, got %v", response.Result().Header)
  4. }

Try to run the test

  1. === RUN TestLeague/it_returns_the_league_table_as_JSON
  2. --- FAIL: TestLeague/it_returns_the_league_table_as_JSON (0.00s)
  3. server_test.go:124: response did not have content-type of application/json, got map[Content-Type:[text/plain; charset=utf-8]]

Write enough code to make it pass

Update leagueHandler

  1. //server.go
  2. func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
  3. w.Header().Set("content-type", "application/json")
  4. json.NewEncoder(w).Encode(p.store.GetLeague())
  5. }

The test should pass.

Refactor

Create a constant for “application/json” and use it in leagueHandler

  1. //server.go
  2. const jsonContentType = "application/json"
  3. func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
  4. w.Header().Set("content-type", jsonContentType)
  5. json.NewEncoder(w).Encode(p.store.GetLeague())
  6. }

Then add a helper for assertContentType.

  1. //server_test.go
  2. func assertContentType(t testing.TB, response *httptest.ResponseRecorder, want string) {
  3. t.Helper()
  4. if response.Result().Header.Get("content-type") != want {
  5. t.Errorf("response did not have content-type of %s, got %v", want, response.Result().Header)
  6. }
  7. }

Use it in the test.

  1. //server_test.go
  2. assertContentType(t, response, jsonContentType)

Now that we have sorted out PlayerServer for now we can turn our attention to InMemoryPlayerStore because right now if we tried to demo this to the product owner /league will not work.

The quickest way for us to get some confidence is to add to our integration test, we can hit the new endpoint and check we get back the correct response from /league.

Write the test first

We can use t.Run to break up this test a bit and we can reuse the helpers from our server tests - again showing the importance of refactoring tests.

  1. //server_integration_test.go
  2. func TestRecordingWinsAndRetrievingThem(t *testing.T) {
  3. store := NewInMemoryPlayerStore()
  4. server := NewPlayerServer(store)
  5. player := "Pepper"
  6. server.ServeHTTP(httptest.NewRecorder(), newPostWinRequest(player))
  7. server.ServeHTTP(httptest.NewRecorder(), newPostWinRequest(player))
  8. server.ServeHTTP(httptest.NewRecorder(), newPostWinRequest(player))
  9. t.Run("get score", func(t *testing.T) {
  10. response := httptest.NewRecorder()
  11. server.ServeHTTP(response, newGetScoreRequest(player))
  12. assertStatus(t, response.Code, http.StatusOK)
  13. assertResponseBody(t, response.Body.String(), "3")
  14. })
  15. t.Run("get league", func(t *testing.T) {
  16. response := httptest.NewRecorder()
  17. server.ServeHTTP(response, newLeagueRequest())
  18. assertStatus(t, response.Code, http.StatusOK)
  19. got := getLeagueFromResponse(t, response.Body)
  20. want := []Player{
  21. {"Pepper", 3},
  22. }
  23. assertLeague(t, got, want)
  24. })
  25. }

Try to run the test

  1. === RUN TestRecordingWinsAndRetrievingThem/get_league
  2. --- FAIL: TestRecordingWinsAndRetrievingThem/get_league (0.00s)
  3. server_integration_test.go:35: got [] want [{Pepper 3}]

Write enough code to make it pass

InMemoryPlayerStore is returning nil when you call GetLeague() so we’ll need to fix that.

  1. //in_memory_player_store.go
  2. func (i *InMemoryPlayerStore) GetLeague() []Player {
  3. var league []Player
  4. for name, wins := range i.store {
  5. league = append(league, Player{name, wins})
  6. }
  7. return league
  8. }

All we need to do is iterate over the map and convert each key/value to a Player.

The test should now pass.

Wrapping up

We’ve continued to safely iterate on our program using TDD, making it support new endpoints in a maintainable way with a router and it can now return JSON for our consumers. In the next chapter, we will cover persisting the data and sorting our league.

What we’ve covered:

  • Routing. The standard library offers you an easy to use type to do routing. It fully embraces the http.Handler interface in that you assign routes to Handlers and the router itself is also a Handler. It does not have some features you might expect though such as path variables (e.g /users/{id}). You can easily parse this information yourself but you might want to consider looking at other routing libraries if it becomes a burden. Most of the popular ones stick to the standard library’s philosophy of also implementing http.Handler.
  • Type embedding. We touched a little on this technique but you can learn more about it from Effective Go. If there is one thing you should take away from this is that it can be extremely useful but always thinking about your public API, only expose what’s appropriate.
  • JSON deserializing and serializing. The standard library makes it very trivial to serialise and deserialise your data. It is also open to configuration and you can customise how these data transformations work if necessary.