Serverless Apps
Team members: Chris
Project started: 31 May 2017
Technology used: Serverless, Node.js, Amazon Web Services
I’ve recently been looking at Serverless, a framework for creating, deploying and monitoring serverless apps and functions.
Microservices are all the rage at the minute, but behind the hype lies a heated debate on the suitability of a distributed approach in place of ‘monoliths’ (see our recommended reading at the end of this article). During some R&D time for Gravitywell Labs I took some time to dive into the process of building and deploying a serverless app.
Quick aside: in this article I’ll be specifically referencing AWS Lambda functions running Node.js modules, but the principles could, and should be applied to whatever particular mix of hosting environments and languages you are using.
A stateless function (in our case a Lambda function) is usually a small part of a wider process, routine or system. This doesn’t mean we get away with treating it as a second class citizen though, we need to develop and test the function with the same care & attention we would bring to any class or module within a monolithic application.
In fact, we’ve got no excuse to not unit test our lambda functions, because they’re stateless and don’t require any special conditions to run.
On our case (Node / AWS Lambda) we can have continuously running unit tests a few simple lines:
npm -i nodeunit onchange npm -i husky --save-dev
And make sure you add the following scripts to your package.json
"scripts": { "precommit": "npm test", "prepush": "npm test", "start": "npm run handler.js", "test": "nodeunit ./tests", "watch": "onchange './tests/*.js' 'handler.js' './lib/*.js' -- npm test" }
Assuming you have a tests directory, a ‘handler.js’ and a lib directory, onchange will watch for changes in those files and re-run your unit tests every time it detects a change. Notice also we’re running the tests before committing and before pushing using husky’s git hooks.
We’re using nodeunit because the test syntax is incredibly simple.
exports.testTargets = function(test, cb){ let targets = require('../lib/targets'); let result = targets.fetch(); test.equals(result.length, 6); test.done(); };
From here, it’s easy enough to configure a post-update git hook to invoke the serverless deploy command to will deploy your changes to AWS.