counterfact icon indicating copy to clipboard operation
counterfact copied to clipboard

Update use of OpenApi examples to allow developers to output the examples from the endpoints

Open dethell opened this issue 1 year ago • 2 comments

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>);
}

dethell avatar Jan 31 '24 22:01 dethell

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.

pmcelhaney avatar Feb 05 '24 17:02 pmcelhaney

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.

pmcelhaney avatar Feb 05 '24 17:02 pmcelhaney