AWS – Writing better code in Node.js for Lambda functions

Hey,

Been a while but finally its time to post some of technical information I accumulated since my last post. Today we will focus on improvements in code from the time you released something aka version 1 into a code base which you can run tests against.

 

The past …

In my last post I described some modular code I started to work on for use with Lambda ( available here ) The code back then contained a lot of redundant blocks ( which I was aware of 😉  ) however it enabled me to focus on making it better. Just to get everyone idea how it did look like here is snippet from initial code commit

And now this is just only portion of  code which been redundant. It was just in single file. Now imagine we have multiple components with multiple files and we need to make a single change into logic which is repeated across all those ?! Madness :/

Therefore it took some time ( as I’m far away from being a js developer 😉 ) but I changed …

Making it better …

by creating classes and also in this way trying to regain control on controlling the lifetime of object’ instances. This also enabled me to start writing tests for my code which I’m really happy about as it help so much in test driven development ( this was inspired by the following article )

  • Write your business logic so that it is separate from your FaaS provider (e.g., AWS Lambda), to keep it provider-independent, reusable and more easily testable.

  • When your business logic is written separately from the FaaS provider, you can write traditional Unit Tests to ensure it is working properly.

  • Write Integration Tests to verify integrations with other services are working correctly.

 

So how does the new code looks like ? Take a sneak peak on  snippet from shared resource

 

Once that is in place we can go ahead and try to …

 

… use the code in our modules/applications

To get all required references we required our resources and use their functions

 

with keeping the above in mind we should not forget to …

 

… test our code 🙂

And that is why for example I got rests which looks like the following now ( using Mocha and Babel ) …

 

Closing thoughts …

So as you can see it all starts to look nice and definitely will get you further if you implement tests. For those interested to see how do I do things here are the links to my repositores on git

 

I hope someone would be able to reuse something for their own needs 😉 Happy coding!

 

Leave a Reply

Your email address will not be published. Required fields are marked *