class-validator: question: not working across node.js modules

We have a project with multiple node.js modules. Several of them use class-validator – but they don’t work together. Each module gets its own instance of the class-validator where the decorators are stored, so they can’t share common class validation. I’ve tried the useContainer method, but that doesn’t resolve the issue.

We need some sort of solution to make all the class-validator module instances work together.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 10
  • Comments: 32 (20 by maintainers)

Commits related to this issue

Most upvoted comments

@NoNameProvided flattening is a workaround, not the solution. What if you have a separate module that store the shared (between frontend and backend) code, like DTOs with class-validator decorators?

Nope. When you require the class, it uses local node_modules, so during development with npm link you will have this problems with class-validator. Been there, done that 😉 I’ve used container with weird initialization (order of require) to make it work but global metadata storage would solve all the issues.

You said you have multiple packages that depend on class-validator, so I guess your dependency manager is not flattening completely or at all the dependency tree across the packages, and you probably end up with multiple copies of the class-validator package. Since its default container is not a true singleton (not the same instance across different class-validator installations) and, also, the getFromContainer function only accepts the class type itself as a key (not gonna be the same across different installations), you always end up with different instances of MetadataStorage across your packages.

class-validator asks the container for the instance of MetadataStorage to use, so to fix this we must make sure we always get a reference to the same instance, even across multiple installations. That can be accomplished by making the container holder a true singleton and also extending the container to work with Symbol and/or strings to query for instances it holds.

Who use the broken npm link feature in 2020? Maybe it’s time to move on to lerna with deps hoisting? Or at least replace npm link with https://github.com/mweststrate/relative-deps.

We have the same issue, but we have a few helper functions to the validation so I created a new package my-validator that contains our helper functions and reexport the class-validator it is a little bit ugly solution but it guaranteed we use the same version of the class-validator in everywhere.

Flattering is a solution, you should use the same class-validator version across modules when using it (both on backend and frontend) to prevent unexpected behavior.

So you are forcing users to do monorepo just because you don’t like global variable for storying metadata (like TypeORM does)? Seems very nice 😃