hayes / pothos

Pothos GraphQL is library for creating GraphQL schemas in typescript using a strongly typed code first approach
https://pothos-graphql.dev
ISC License
2.32k stars 158 forks source link

validation plugin: Setting errormap on zod #1226

Closed ewen-lbh closed 3 months ago

ewen-lbh commented 3 months ago

I'm wondering how I would use z.setErrorMap so that the validation plugin recognizes it (I tried to just do that and it doesn't work).

I know that you can override the thrown error, but I'm looking for something more high-level.

The use-case is to localize Zod error messages in another language, through zod-i18n

I tried the following:

import i18next from 'i18next';
import { z } from 'zod';
import { zodI18nMap } from 'zod-i18n-map';
import  { zodTranslations } from '(somewhere)';

i18next.init({
  lng: 'fr',
  resources: {
    fr: { zod: zodTranslations },
  },
});
z.setErrorMap(zodI18nMap);

...both before and after instanciating the builder, to no avail. I'm guessing that pothos-validation has its own zod object and that it's not global shared state

hayes commented 3 months ago

It looks to me like error maps do get applied correctly for the individual validation messages, but you may need to combine the individual errors manually.

Here's a simple example that just takes the first error and creates a new error using the message from that issue: https://stackblitz.com/edit/typescript-mhtnwd?file=index.ts

ewen-lbh commented 3 months ago

Hi! Thanks for the quick response. As it turns out, it was a weird bug with the other library, that I worked around by explicitly passing i18next's t to the lib's error map:


import i18next from 'i18next';
import { z } from 'zod';
import { makeZodI18nMap } from 'zod-i18n-map';
import  { zodTranslations } from '(somewhere)';

i18next.init({
  lng: 'fr',
  resources: {
    fr: { zod: zodTranslations },
  },
});
z.setErrorMap(makeZodI18nMap({ t: i18next.t }));
...