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.36k stars 200 forks source link

How can I assign a value to a data variable #947

Closed Dunga999 closed 1 year ago

Dunga999 commented 1 year ago

How can I assign a value to a variable that I can use latter when templating. Looking for examples I came with something like:

{{#assign 'data'}}{{array 'a' 'b' 'c'}}{{/assign}}
...
{{#each ({{data}}) as |value|}}
   {{value}}
{{/each}}

But I can't make it work. Somehow #assign is not recognized. Is this the correct way to do it?

By the way, You have made a great tool. Thank you

StefH commented 1 year ago

I don't know if "#assign" works.

But you can also just define a Data field with some static data.

See this issue for more details https://github.com/WireMock-Net/WireMock.Net/issues/892

Dunga999 commented 1 year ago

Yes, I have crossed that option, but I need a more dynamic (not static) data. My full need is that I'm receiving a request with an ID and with that ID I need to query a DB to gather specific data for the response. My issue is how to pass this dynamic data when templating.

StefH commented 1 year ago

If you have an ID in the request parameter or body, you can use get that value and return it in the response.

See also https://github.com/WireMock-Net/WireMock.Net/wiki/Response-Templating

StefH commented 1 year ago

@Dunga999 Does my proposed solution work for you?

Dunga999 commented 1 year ago

Hi @StefH,

Thanks for the follow up. As I said, I need to handle dynamic data, so your solution didn't directly attend my needs, but pointed me a way to handle the requirement. I created an helper to save the dynamic data in the Data field so I could access it in the templating. I think I didn't gave you the full view of the dynamic data requirement, but I implemented something like this:

{{save 'invoice' (query 'connectionId' 'SELECT col1, col2 FROM Invoice WHERE InvoiceId=@id' id=(request.pathsegments.[3])) }} ... {{#each (Data.invoice) as |item|}} ... "invoiceId": "{{item.col1}}", ... {{/each}}

Being, "save" and "query" the helpers I created.

Again, thank you for the suggestion and for this amazing tool