How To Structure Multi-Service Codebase With Shared Library Code


#1

Does anyone have any suggestions on how to structure a codebase that contains multiple services and has some library code that can be shared between various services? For example:

my-project
  - services
    - foo-service
      - serverless.yml
      - src/FooService.js
    - bar-service
      - serverless.yml
      - src/FooService.js
  - lib/src/SomeSharedLibrary.js

If you then have this in your serverless.yml file:

package:
  include:
    '../lib/src/**'

Your zip that serverless builds will result in this:

src/FooService.js
lib/src/SomeSharedLibrary.js

So in FooService.js you must reference SomeSharedLibrary with ../lib/src/SomeSharedLibrary even though the real path is ../../lib/src/SomeSharedLibrary (notice the extra level of nesting).

That works, except then tests won’t work because when you run tests FooService can’t find SomeSharedLibrary.

So, it seems that either:

  1. I need to have a different way of structuring the codebase with the shared code, or
  2. I need to do some magic for testing to make it mimic the directory structure that Serverless will create for my deployed code, or
  3. I need to use symlinks or something to make the lib code appear inside the service that uses it.

#2

It sounds like you simply need to use a package manager, and then import (es6) or require the package after installing it with npm or yarn.

If your shared code can be made public, publish it as libraries to NPM.

If not, consider having a private NPM registry. Alternatively, you can include packages with direct references to private github repositories.