Develop my first Serverless App

Develop my first Serverless App

When I decided to play a little bit with this technology I started reading AWS Lambda web page. Personally I don’t like AWS documentation pages, and I was so confused about it.

The first thing you see when creating a lambda application is this: 

 

AWS Lambda trigger select

AWS Lambda trigger select

First of all, you should select what event will trigger your lambda function. As you can see, there’s a lot of options for cool integrations. For now we’ll use the API Gateway, this means that every time a user makes an HTTP request, it will run the function.

And here comes my problem with this platform:

<creating a lambda functionp class=”wp-caption-text”>Create your Lambda function

This is the interface for creating the lambda function, an online editor! Yeah, it’s true, there are other options like uploading the file with a ZIP or from S3 but come on, where is my CLI or a proper deployment system from a terminal? Also, this way I have to manage my lambda functions one by one. I would like to find a way to manage the functions all together.

At this time I decided to find another way of doing this.

Serverless (link here) is a JavaScript framework that helps you create this type of applications. First of all, we have to know that this one isn’t like Express nor Ruby on Rails, this one will help us create all the functions we want to code at once (in one project) and will help us deploying it into our service provider. All the syntax you see, all the protocol you have to follow when writing, these are from the service provider, not the framework.

Create the project

For creating your project you should run this code in your terminal:

# Install serverless globally
npm install serverless -g
# Create an AWS Lambda function in Node.js
serverless create –template aws-nodejs –path my-serverless-app
view rawcreate-serverless-app.sh hosted with ❤ by GitHub

Once the project is created, you will see two files (aside from the .gitignore): handler.js and serverless.yml.

Severless.yml

Serverless.yml is the yaml configuration file for the framework. In it, you’ll tell the framework all the things related to the service and how it should deploy it on the service provider. It’s pretty self-explanatory since it’s full of comments guiding you through the process. By now, we’ll use this one:

#
# This file is the main config file for your service.
# It’s very minimal at this point and uses default values.
# You can always add more config options for more control.
# We’ve included some commented out config examples here.
# Just uncomment any of them to get that config option.
#
# For full config options, check the docs:
# docs.serverless.com
#
# Happy Coding!
service: my-serverless-application
provider:
name: aws
runtime: nodejs6.10
functions:
hello:
handler: handler.hello
events:
http:
path: users/create
method: get
view rawserverless.yml hosted with ❤ by GitHub

The service is the name of our service. The provider contains the information about our service provider like which one are we using (aws in this case) and the dependencies attached to it (in this project we’re using node v6.10). The last property we’re defining is the list of functions, in it we’re defining the list of functions that the framework will configure and upload in our service. On every function, we’re defining a handler and the events that trigger that function. The handler is composed by the file and the function reference separated by a dot and the events property is a list. In that list, we’re executing that function every http request on /user/create path on a GET method. Serverless will get that list and, for every function, will upload it to the service provider and configure every event that will trigger it.

As we pointed before, it’s plenty of options for function triggers. When a user uploads an image on S3, or when he deletes it; When another app in your AWS system enqueues a message on SNS; On a periodic interval, when you set it up as a cron job with a schedule event… You can check the list of optinons in here.

handlers.js

Then we follow with the handlers.js file:

use strict;
module.exports.hello = (event, context, callback) => {
const response = {
message: hello world!
}
callback(null, response);
};
view rawhandler.js hosted with ❤ by GitHub

We should remember that all the contents in this file are following the AWS Lambda protocol, so you should refer to this service provider documentation to solve or learn something related to it. This hello world will help us understand easily the format of the function. First rule: we have to export every function we want to declare, and we’ll accept three arguments on its signature: event, context and the callback.

The event is an object containing the information related to the event that triggered the function execution. The context is an object containing information and method to access to the AWS Lambda instance context (more info). Finally the callback, is a function that we’ll call with the response of the execution. Actually, we can set up the event so it expects the function as synchronous but, come on, we’re on JS, let’s embrace asynchronicity.

Finally, we create an object and we call the callback with no errors, generating the response and sending it back to the client.

Deploy it

It’s time to deploy. First of all we need to set up our AWS Credentials. For that, we should go to AWS IAM (identity and access management, security credentials) and create a new Access Key. After it, copy the access key and the access secret and run the next command in the terminal (interpolating these 2 values):

serverless config credentials –provider aws –key [access_key] –secret [access_secret]
view rawserverless-set-credentials.sh hosted with ❤ by GitHub

Finally, deploy it. The process will take several minutes, don’t worry, it only take so much time on the first deployment.

serverless deploy
view rawserverless-deploy.sh hosted with ❤ by GitHub

Once deployed, you will se a screen like this one:

terminal output of deployment

Go to the the listed url and BOOM! Function executed 🙂

Deployment Stages

Keep in mind that we just uploaded this function to the development stage. If you want to deploy it to production just add --stage production flag to the deployment command. You can also specify the region with the --region flag.

Database connection (to MongoDB)

In case you want to connect your function to a database, here you have an example of how to do it:

module.exports.hello = (event, context, callback) => {
const url = mongodb://user:password@mydatabase.mlab.com/serverless
require(mongodb).MongoClient.connect(url, (err, db) => {
const User = db.collection(User)
User.insert({
name: arol
}, (err, newUser) => {
let response;
if(err) {
response = {
statusCode: 400
}
}
response = {
statusCode: 200,
body: newUser,
};
callback(null, response);
db.close();
})
view rawhandler.js hosted with ❤ by GitHub

Despite the code quality of this example, it includes the key concepts. The most important is to require your dependencies inside the same function. If you do it outside, like we do in a normal server, it may be released and you won’t have access to it inside the function. You can install dependencies setting up a npm package and performing an npm install.

That’s all for now! We demystified serverless applications and we learnt how to create one. Try things, play with it, then come back and share your experience and your learnings in the comments section. Hope it helped you!

Build Serverless REST API quickly with the Serverless Framework

3 Comments

  1. Arvind Kumar July 19, 2017 Reply

Add a Comment

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