zoubingwu / msw-auto-mock

A cli tool to generate random mock data from OpenAPI definition for msw.
273 stars 57 forks source link

Suggestion: Support multiple examples in faking data #17

Open dwjohnston opened 1 year ago

dwjohnston commented 1 year ago

Use of the example property works well.

eg. for a Pet schema like:

{
  "type": "object",
  "required": [
    "id",
    "name"
  ],
  "properties": {
    "id": {
      "type": "integer",
      "format": "int64"
    },
    "name": {
      "type": "string", 
      "example": "Fido"
    },
    "tag": {
      "type": "string"
    }
  }
}

We get the generated code:

  rest.get(`${baseURL}/pets/:id`, (req, res, ctx) => {
    const resultArray = [
      [
        ctx.status(200),
        ctx.json({
          id: faker.datatype.number(),
          name: "Fido",  //<--- Generated from example 
          tag: faker.lorem.slug(1),
        }),
      ],
      [
        ctx.status(NaN),
        ctx.json({
          code: faker.datatype.number(),
          message: faker.lorem.slug(1),
        }),
      ],
    ];

    return res(...resultArray[next() % resultArray.length]);
  }),

What would be really nice is to be able to provide multiple examples, eg:

{
  "type": "object",
  "required": [
    "id",
    "name"
  ],
  "properties": {
    "id": {
      "type": "integer",
      "format": "int64"
    },
    "name": {
      "type": "string", 
      "examples": {
        "1": {
          "value": "Fido"
        }, 
        "2": {
          "value": "Rex"
        }
      }
    },
    "tag": {
      "type": "string"
    }
  }
}

Generates the code:

  rest.get(`${baseURL}/pets/:id`, (req, res, ctx) => {

    const examplesMap = {
      "1": "Fido", 
      "2": "Rex"
    }

    const resultArray = [
      [
        ctx.status(200),
        ctx.json({
          id: faker.datatype.number(),
          name: examplesMap[req.params.id],
          tag: faker.lorem.slug(1),
        }),
      ],
      [
        ctx.status(NaN),
        ctx.json({
          code: faker.datatype.number(),
          message: faker.lorem.slug(1),
        }),
      ],
    ];

    return res(...resultArray[next() % resultArray.length]);
  }),

I guess the thing that's potentially problematic with this, is that as a convention I'm assuming that the request parameter matches the example key... which won't necessarily be the case?

Anyway - fantastic work with this.