Friday 2 June 2017

Serverless Node.js Project Structure

I am building a RESTful API with the serverless framework to run on AWS (API Gateway + Lambda + DynamoDB). It's my first Node project and my first serverless production project and I have no idea how to structure it. So far I have the following |--Functions |-----Function1 |--------InternalModule |-----Function2 |-----Function3 |--------InternalModule |-----Function4 |--Shared |-----Module1 |-----Module2 |-----Module3 |--Tests |-----Functions |--------Function1 |-----------InternalModule |--------Function2 |-----------InternalModule |--------Function3 |-----------InternalModule |--------Function4 |-----------InternalModule |-----Modules |--------Module1 |-----------InternalModule |--------Module2 |-----------InternalModule |--------Module3 |-----------InternalModule I keep my API endpoints (Lambda handlers) in Functions. Some of them have internal modules which they only use and there are some who use modules from Shared. I want to have unit tests for all my modules - inner and shared as well as API testing on the lambda functions. I am using mocha and chai and want to integrate everything in a pipeline which on a git push runs the linters and tests and if they are successful deploy the API to the appropriate stage. The problem is that in order to test each module I have to have chai as a local node module in every folder where I have a test file and reference the modules to be tested by a relative path. In most cases it looks really ugly because of the nesting. If I want to test an internal module from Tests/Functions/Function1/InternalModule and I require it on top of the test like so require('../../../../Tests/Functions/Function1/InternalModule') + I have to install chai in every folder so it's reachable. The same goes for mocha and all the dependencies needed for the test and I haven't even mentioned configuration. The main idea I am now considering is weather or not I should bring all modules to a folder called modules and require them when needed - worst case from Functions/Function1 require('../../Modules/Module1') Also keep the test files in the module folder and run them inside, but that would require the assertion library installed in every folder. I've read about npm link and symlinks but I want to keep track of what dependencies each folder has so I can install them on the CI environment after the clean project is downloaded from GitHub where I can't do links (or I've got the whole concept wrong?)

If anyone can suggest a better solution I would highly appreciate it!



via Daniel Papukchiev

No comments:

Post a Comment