Denrox/nestjs-microservices-example

sharing code between microservices

ais-one opened this issue · 1 comments

How do we share code if something like the file below is used by multiple microservices?

https://github.com/Denrox/nestjs-microservices-example/blob/master/user/src/services/config/mongo-config.service.ts

Also will npm workspace be used when it is available in node 16 LTS?

Anyway thank you for this very informative example...

Hi, such files as the mentioned one (mongo-config.service.ts) should never be shared between microservices. Because the DB config for every microservice instance should be separate and different in real life.

Regarding code sharing in general, the microservice approach for sharing large parts of functionality is to separate them into a completely separate microservice and send commands to that microservice via TCP socket, Redis pubsub, or whatever another channel.

Regarding sharing small parts of code, you have several ways for it:

  • if the code of your services is located in a separate git repos, then code that has to be shared should be published to a private npm repo (verdaccio, nexus, etc), and imported via npm deps in package.json
  • if the code of all your microservices is located in a single git repo (which is also not correct for real apps), then you just create some folder like "shared" in the root folder of your repo. For development, you can use symlinks in a microservice folder where you want to use it + import inside the .ts file. And for production you will need to add an extra comment in your Dockerfile to copy the shared folder inside the docker image.

But again sharing code between microservices is a very contradictory practice.