Interested in callbacks?
Hello again.
Having played with the API a bit I was struggling to implement a stub where I needed a tiny bit more logic in creating the response, for example to do string manipulation on the request in a more granular way than handlebars, or in generating new IDs say.
I have experimented with a callback API like this:
server.Given(Request.Create()
.WithPath("/foo")
.UsingGet())
.RespondWith(Response.Create()
.WithCallback(req => new ResponseMessage {Body = req.Path + "Bar"}));
The minimal implementation is in my fork, see the comparison: https://github.com/WireMock-Net/WireMock.Net/compare/master...alastairtree:feat/callbacks?expand=1
Is this something you would be interested in? Happy to do some extra work if needed to get something like it adopted. I noticed it also came up in Mock4net (https://github.com/alexvictoor/mock4net/issues/19)
Thanks for the great library
Alastair
Hi Alastair. This sounds ok.
However maybe the names should be WithResponseFunc and WithResponseFuncAsync. (We would also need the async version if possible.)
Some code is already there in DynamicResponseProvider.cs, however we cannot reuse those classes.
Would this be an idea?
Hi, looks like a great way to provide access to the request! What can I do to help?
@joostvanhassel Thanks for helping out. I think that the code from @alastairtree is a good start, and maybe already enough to get this issue solved?
@StefH the changes as proposed by @alastairtree do fully cover what I would like to do for now. I think it is good to take these changes in and improve later on if further if needed.
OK. Currently I'm working on issue https://github.com/WireMock-Net/WireMock.Net/issues/91, this needs to be solved 100% before I continue on this one. So if you have time, you can also review this issue.
Added to the source-code.
@StefH thanks - this looks pretty good! Been thinking about syntax a bit, it is worth adding an overload on the WithBody() response builder method in addition that accepts a func<RequestMessage,string> something like the below. Would probably be a nice productivity gain and makes it easy for the majority case where you just want to build the body string dynamically?
server
.Given(
Request.Create().WithPath("/some/thing").UsingGet()
)
.RespondWith(
Response.Create()
.WithStatusCode(200)
.WithBody(req => $"{{ path : '{req.Path}' }}")
);
I have added a PR and test to show what i mean, see #102