WireMock-Net / WireMock.Net

WireMock.Net is a flexible product for stubbing and mocking web HTTP responses using advanced request matching and response templating. Based on the functionality from http://WireMock.org, but extended with more functionality.
Apache License 2.0
1.35k stars 197 forks source link

Is there a way to access templated data after transformation? #1064

Closed vovka15 closed 4 months ago

vovka15 commented 4 months ago

Hello!

Question:

Is there a way to access templated data after transformation?

Context:

I am trying to perform some operations on response body AFTER transformation happened and THEN respond with modified body.

Example:

Request:

{
    "field": "value",
    "description": "desc"
}

I have possibility to access it's body by using templates. So code would look like this:

    server
        .Given(
            Request.Create().WithPath("/path").UsingPost()
        )
        .RespondWith(
            Response.Create()
                .WithStatusCode(200)
                .WithBody(" {{ request.body }} "))
                .WithTransformer()
    );

But the problem is I want to modify some fields of that request and add new field that depends on values that arrive in the given request - for example, operation that concatenates all received fields and returns base64 value of it.

So I want to pass received request in some function, manipulate it's data and only then return response.

I've tried that stupid solution, but it of course doesn't work.

    server
        .Given(
            Request.Create().WithPath("/path").UsingPost()
        )
        .RespondWith(
            Response.Create()
                .WithStatusCode(200)
                .WithBody(SomeFunction(" {{ request.body }} ")))
                .WithTransformer()
    );

Maybe there is solution, but I did not find any in the current wiki.

Can you please tell is there possibility to do that?

StefH commented 4 months ago

@vovka15 A possible way would be to use the existing Handlebars functions, see the documentation from Handlebars.Net for details. In case, there is no function available, maybe a function is present in https://github.com/Handlebars-Net/Handlebars.Net.Helpers (for example Dynamic

If that is also not enough, you can write the function in c# with: WithBody and a callback function --> https://github.com/WireMock-Net/WireMock.Net/blob/master/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs#L29

vovka15 commented 4 months ago

Thanks for suggestions! I will report later after tests

vovka15 commented 4 months ago

I used second variant and it works like a charm. Thanks a lot!