kubb-labs / kubb

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

Pass data to MSW handlers, like the create fake data functions. #1114

Closed stijnvanhulle closed 3 weeks ago

stijnvanhulle commented 3 months ago

Discussed in https://github.com/kubb-labs/kubb/discussions/1062

Originally posted by Samuel-Morgan-Tyghe July 1, 2024 So theres alot of uses for passing in hardcoded values to our fake data, but to utilize this we then have to pass it into a handler.

why not pass data directly into the handler into the handler?

import { http } from "msw";
import { createGetProductSummaryMutationResponse } from "../../mocks/retail/createGetProductSummary";

export const getProductSummaryHandler = (extendedData) => http.post("*/v2/products/summary", function handler() {
    return new Response(JSON.stringify(createGetProductSummaryMutationResponse(extendedData)), {
        headers: {
            "Content-Type": "application/json",
        },
    });
});
export function createGetProductSummaryMutationResponse(extendedData): NonNullable<GetProductSummaryMutationResponse> {
    faker.seed([100]);
    return createProductSummary(extendedData);
}
cthompson-avb commented 1 month ago

I would also like to see plugin-faker decoupled from plugin-msw.

While faker is useful, I generally prefer to have my msw handlers return known, static, data rather than randomly generated values.

stijnvanhulle commented 1 month ago

@cthompson-avb And how would you provide your static data? The only thing I can think of is something like this: This means the data needs to be provided in every handler. As in, defining the data will be outside of Kubb.

export const addPetHandler = (data: Partial<Pet>)=>  http.post('*/pet', function handler(info) {
  return new Response(JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json',
    },
  })
})
stijnvanhulle commented 3 weeks ago

@cthompson-avb v3 of Kubb now has a possibility to use msw without the faker plugin: https://v3.kubb.dev/plugins/plugin-msw/#parser. Set parser to 'data' and faker will not be used.