How to create a structured Typescript & Serverless function
We recommend you use an identifier to help log processes within functions and our sample code to produce standardized functions.
This article makes use of code that is available in our Open Source Serverless & Typescript starter project and discusses the best practices for creating structured functions.
Sample Code
File Location
We recommend creating one file per function, placing all functions in the functions folder and exporting the handler as demonstrated using module.exports.handler = handler. This can then be accessed in the serverless.yml through functions/filename.handler, where filename is the name of the file that sits within the functions folder.
Standardize Imports
At the top of the file, we have left comments which indicate the order and where we suggest that you import functions. This helps increase operational efficiency and provides a means for developers to quickly know what's in a file.
Identifier
The sample code found above is available in our Open Source project and makes use of a unique identifier to help log responses and keep track of how processes are evolving, when they succeed and if they fail, why they fail and where.
Standardized Responses
We recommend using standardized responses, which are available in the Open Source project and which are detailed in the article below.
Reduce Cyclomatic Complexity
To reduce the difficulty of analyzing code, we recommend that you breakdown the functionality into reusable modules which are analyzed in a separate area, which could be called support functionality - which executes functionality and handles successes or failures.
An example of this can be found at the bottom of our sample code and details that we would treat a successful sending of emails with a successful response; and a failure to send the emails with a failed response.
Any Questions?
We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.