Skip to content

feat(zod-mock): pass path context to stringMap callbacks - #271

Open
matt-halliday wants to merge 3 commits into
anatine:mainfrom
matt-halliday:feat/mapper-context
Open

feat(zod-mock): pass path context to stringMap callbacks#271
matt-halliday wants to merge 3 commits into
anatine:mainfrom
matt-halliday:feat/mapper-context

Conversation

@matt-halliday

@matt-halliday matt-halliday commented Jul 10, 2026

Copy link
Copy Markdown

Problem

stringMap callbacks have no way to distinguish where in the schema a field was located. If the same field name (e.g. name) appeared under different parent objects, every instance received the same generated value, making it impossible to, say, produce an institution name vs. a person's name from a single name entry.

Limitation also highlighted in these issues, though this is arguably a more discrete solution than deep object stringMap support, or docblock/annotation parsing, and provides support for arrays and tuples if needed:
#141
#134

Proposed Solution

stringMap callbacks now receive a ctx argument with a path: (string | number)[] property, following the same convention used by Zod's own error objects, representing the full path to the current field.

const model = z.object({
  student:     z.object({ name: z.string() }),
  institution: z.object({ name: z.string() }),
});

generateMock(model, {
  stringMap: {
    name: ({ path }) =>
      path.includes('institution')
        ? faker.company.name()
        : faker.person.fullName(),
  },
});

Changes

  • zod-mock.ts: parseObject now accumulates _path on options as it recurses, parseString passes { path } when invoking a stringMap generator.
  • GenerateMockOptions: stringMap type updated from (...args: any[]) => string to ctx: StringMapContext) => string. _path added as an @internal field.
  • StringMapContext: new exported interface

Backwards compatibility

Existing callbacks continue to work, the extra argument is silently ignored. All existing tests pass. One new test added.

The context is also an object so additions in future might be added without impacting any new consumers of this path implementation.

@nx-cloud

nx-cloud Bot commented Jul 10, 2026

Copy link
Copy Markdown

View your CI Pipeline Execution ↗ for commit e4d945c

Command Status Duration Result
nx affected:test --base=origin/main --codeCoverage ✅ Succeeded 5s View ↗
nx affected:lint --base=origin/main ✅ Succeeded 2s View ↗

💡 Verify your cache is correct by running tasks in a sandbox. Read docs ↗


☁️ Nx Cloud last updated this comment at 2026-07-10 11:52:41 UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant