dcohenb
dcohenb

Reputation: 2127

sharing code between microservices

I have a suite i'm working on that has a few micro-services working togther. I'm using Docker to setup the environment and it works great.

My project components are as follows:

As you can probably guess the 2 Node.js servers are suppose to work with the same DB. Now I've defined my models in one of the projects but I'm wondering what is the best practice when it comes to handling the second. I would really love to avoid copy pasting my code because that means I have to keep both of them up to date when I do changes to the Schema. is there a good way to share the code between them?

my project looks like this:

rest-api // My first Node.js application
    models
        MyFirstModel.js // This is identical to the one in the worker/models folder
        MySecondModel.js
    index.js
    package.json
    Dockerfile
worker // My second Node.js application
    models
        MyFirstModel.js
        MySecondModel.js
    index.js
    package.json
    Dockerfile
docker-compose.yml

Any input will be helpful.

Thanks.

Upvotes: 4

Views: 2966

Answers (2)

Gergo
Gergo

Reputation: 2290

The common opinion is the following: two microservices should not share same data model. There are several article about it and some question related to this topic.

How to deal with shared models in micro service architectures

However I think there are some cases when you need it and acceptable. Trust is a luxury even if everything is internal, thus security and conformity must be considered. Any incoming object must be normalised, validated and checked before initiate any process with it. The two service should handle the data with the same way.

My solution that I used for an API and an Admin services which shared the models: I created 3 repositories, one for the API and one for the Admin and a 3th one for the models directory. Models should be present in both repositories so and I added it as a git submodule. Whenever you change something on a schema, you should commit it separately, but I think it is the best solution to manage the changes without duplicating the code.

Upvotes: 1

Fares
Fares

Reputation: 531

Of course you can. What you have to do is to put your common files in an volume, and share this volume with both Node containers.

You should setup a data volume in which you put all the files you want to share. More about this here or anywhere else by googling it. Cheers.

Upvotes: 1

Related Questions