Update use of OpenApi examples to allow developers to output the examples from the endpoints
Various discussion has happened around having Counterfact record/capture network sessions to capture sample JSON data responses that can be returned by default by the generated endpoints instead of .random().
After discussing it seems like a separate tool that converts a HAR file to OpenAPI is the best companion (such as https://github.com/jonluca/har-to-openapi). For the Counterfact side, presently, if an example is present, CF will pick one at random. This ticket asks for the ability to give access to the OpenApi examples so a developer can choose to use them as output or even use the examples within a context.
Example 1 (inside an endpoint TS file):
return $.response[200].examples.namedExample1
Example 2 (inside a Context):
return $.response[200].json($.context.someFunction())
and then in the context:
public function someFunction() {
const baseData = this.spec.examples.namedExample1;
return baseData.filter(item => <some filter logic>);
}
Looks like there's another feature implied in your second example: that the context has access to the OpenAPI spec. That makes sense to me. It can be passed in the constructor of the Context class.
Instead of
return $.response[200].examples.namedExample1
In order to keep the fluent API, we may need to do:
return $.response[200].example("namedExample1")
The reason for that is it allows continue decorating the response after selecting its content:
return $.response[200].example("namedExample1").header("some-header", "some-value")
There are two parts to implementing this feature. The runtime part can be implementing by making a copy of this random() function.
https://github.com/pmcelhaney/counterfact/blob/b8d7ca5e7fdd6f8601b3a20206fbd0c779edcff1/src/server/response-builder.ts#L101-L137
Instead of using the oneOf() function to randomly select an example it would select the specific example passed to the function.
The other part is the ResponseBuilderFactory type:
https://github.com/pmcelhaney/counterfact/blob/f29e14373660f3c8712349679b9bda95f9a0476c/src/server/types.d.ts#L93-L109
It will look a lot like random. The only exception is the function signature takes one argument, name: keyof Response["examples"] or something like that.