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
- fix: avoiding metadataStorage from DI (#335) Closes #328. Closes #261. Closes #132. — committed to typestack/class-validator by satanTime 4 years ago
@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-validatordecorators?Nope. When you require the class, it uses local node_modules, so during development with
npm linkyou will have this problems withclass-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
getFromContainerfunction only accepts the class type itself as a key (not gonna be the same across different installations), you always end up with different instances ofMetadataStorageacross your packages.class-validator asks the container for the instance of
MetadataStorageto 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-validatorthat contains our helper functions and reexport theclass-validatorit is a little bit ugly solution but it guaranteed we use the same version of theclass-validatorin everywhere.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 😃