kubb-labs / kubb

The ultimate toolkit for working with APIs.
https://kubb.dev
MIT License
737 stars 68 forks source link

Support Dynamic and Customizable Data in Handlers for `@kubb/plugin-msw` #1427

Open wmahad opened 2 days ago

wmahad commented 2 days ago

What is the problem this feature would solve?

I propose adding support to @kubb/plugin-msw for passing either a data object or a function as a parameter to handlers. This would allow users to customize the behavior of handlers dynamically, making mocking and testing much more flexible.

Example

Here's an example implementation to illustrate the idea:

export function apiKeysUpdateHandler(
  data?: ApiKeysUpdateMutationResponse | Function,
  options = {}
) {
  return http.put('*/api/v2/api-keys/:uuid/', function handler(info) {
    if (isFunction(data)) return data(info);

    return new Response(
      JSON.stringify(createApiKeysUpdateMutationResponse(data)),
      {
        headers: {
          'Content-Type': 'application/json',
        },
        ...options,
      }
    );
  });
}

Use Case

This would enable users to customize handlers as shown below:

apiKeysUpdateHandler(({ params }) => {
  if (params.someKey) {
    return new Response(
      JSON.stringify({ error: 'some error response' }),
      { status: 400 }
    );
  }
  return new Response(
    JSON.stringify({ newData: 'new data' }),
    { status: 200 }
  );
});

Benefits

Reference

This feature is inspired by a similar capability in Orval.

linear[bot] commented 2 days ago

KUBB-77 Support Dynamic and Customizable Data in Handlers for `@kubb/plugin-msw`