chrishoermann / zod-prisma-types

Generator creates zod types for your prisma models with advanced validation
Other
626 stars 47 forks source link

Support of i18n for validation error messages #142

Open cimchd opened 1 year ago

cimchd commented 1 year ago

First of all: Great work, zod-prisma-types really fits perfect in our project setup. :-)

We are facing the issue, that we want to internationalize our application and we only found a way to create custom error messages with zod-prisma-types on a field level.

We would like to replace all of the zod default error messages on a project level at once (see: https://github.com/aiji42/zod-i18n). Did we miss something and is this already possible?

If not it would be perfect if we could get an option to extend the root zod instance. For i18n we want to do something like this:

import { zodI18nMap } from "zod-i18n-map";

function extendZod(z) {
  z.setErrorMap(zodI18nMap);
}
chrishoermann commented 1 year ago

@cimchd this seems like a cool addition but I don't really have experience with i18n or the package you mentiond so I need to dig into your link a bit. Could you also help me out with some examples on how this could/should look like for a sample prisma schema?

cimchd commented 1 year ago

@cimchd this seems like a cool addition but I don't really have experience with i18n or the package you mentiond so I need to dig into your link a bit. Could you also help me out with some examples on how this could/should look like for a sample prisma schema?

Sure :-)

The question is how the api should look like. It needs to be able to run setErrorMap on the zod object. Here are some options:

  1. If we want to add a generator option only for the zod-i18n-map-package you could enable it by a special option like:
    generator zod {
    provider           = "zod-prisma-types"
    enableI18nErrorMap = true
    }
  2. A more general option could be to allow any import for an error mapping:
    /// @zod.import(["import { zodI18nMap} from 'zod-i18n-map';"])
    generator zod {
    provider            = "zod-prisma-types"
    customErrorMap      = "zodI18nMap"
    }
  3. And even more general could be to allow extending the zod instance
    generator zod {
    provider         = "zod-prisma-types"
    extendZod        = "extend-zod.js"
    }

    Where extendZod expects a script that exports an extendZod function:

    
    // extend-zod.js
    import { zodI18nMap } from "zod-i18n-map";

export function extendZod(z) { z.setErrorMap(zodI18nMap); }