anatine / zod-plugins

Plugins and utilities for Zod
659 stars 92 forks source link

[zod-mock] nested string mapping #141

Open ispringle opened 1 year ago

ispringle commented 1 year ago

I'm working on generating mock data from zod schemas. Currently just working on developing a string map to provide that will generate the correct mocks, but I'd like to ultimately figure out how to provide hinting in the zod schemas to generate better mock data (#134).

One thing I'm currently struggling with is that the string map is just a 1-D object, each key must have a value that is either a string, number, etc. or a function that returns the same. I'm wondering if it'd be possible to instead generate a map that more closely maps to the zod schema, ie. an n-D object.

If I had the zod schema:

{
  result: {
    status: z.string(),
   errorCode: z.number(),
  },
  user: {
    name: z.string(),
    ...,
  },
  institution: {
    name: z.string(),
    ...,
  },
  ...
}

I'd like to be able to define my mappings like:

{
  user: {
    name: faker.person.fullName,
  },
  institution: {
    name: faker.company.name,
  },
}

Currently if I have multiple objects in my schema that use the same key, such as both user and institution having a name key, they'd both use the same Faker type. Current solution I have is to spread more specific data over the data generated, ie the mapping would be:

{
  name: faker.person.fullName,
}

and then I mutate the object returned by zod-mock:

return {
  ...generateMock(Schema, ),
  ...{
    institution:
      name: faker.company.name(),
    },
  }
}

But it'd be nice if this could be handled by zod-mock.

One option I think might be simply is to allow the mapping keys to return an object or array, this way you can more finally control the mock data.