Dean Mraz

I am passionate about delivering ideas and spending most of my time on product management techniques.

February 12th 2019

Services Pattern Tutorial with Serverless Framework, Nodejs and Webpack

serverless-nodejs-webpack

Services Pattern

A Service Layer that share common functionality. In a Nodejs project this can mean the CRUD operation on a model. CRUD = Create, Read, Update and Delete.

Benefits

  • Couple operations on a model
  • Decouple models from each other
  • Single entrypoint to make requests on a model

Serverless Framework

Serverless Framework with AWS Provider helps you develop and deploy your AWS Lambda functions, along with the AWS infrastructure resources they require.

Webpack

Webpack is a static module bundler for modern JavaScript applications.

Benefits

  • Compiler Configuration
  • Module Aliases
  • Loaders
  • Next Generation JavaScript with Babel Loader
  • Immutable builds

Setup

  1. Create a new service with Serverless Framework.
  2. Install Serverless Offline and Serverless Webpack
  3. Configure the serverless.yml
service: controllers # NOTE: update this with your service name

plugins:
  - serverless-webpack
  - serverless-offline

provider:
  name: aws
  runtime: nodejs8.10
  stage: master
  region: us-west-2

Configure Webpack

Leverage serverless-webpack to handle the entrypoints. This is beneficial as you only have to configure the function handlers in the serverless.yml file.

const slsw = require('serverless-webpack');
// more requires… 

module.exports = {
  entry: {
    ...slsw.lib.entries,
  },
// more webpack config… 
};

Setup the function endpoints

In the serverless.yml file add

// previous serverless.yml 
functions:
  users:
    handler: app/controllers/users.default
    events:
      - http:
          path: api/users/{proxy+}
          method: any

Note: If you disapprove of the Services Pattern and would rather opt for Microservice Pattern then you can implement each http method in separate functions and specifying the http method in the events.

Add the Code

In app/controllers directory you can add the function logic. I typically separate validating and normalizing the data in the controller and pass that down to a model. I can write more on this in another article.

//app/controllers/users.js

class UsersController {
  async handle(event, context) {
    try {
      const method = event.httpMethod.toLowerCase();
      return await this[method](event, context);
    } catch (e) {
      console.error(e);
      return {
        statusCode: 500,
        body: JSON.stringify({ error: true }),
      };
    }
  }

  async get(/*event , context*/) {
    return {
      statusCode: 200,
      body: JSON.stringify({
        users: [], // retrieve from data source
      }),
    };
  }

  async post(/*event , context*/) {
    return {
      statusCode: 200,
      body: JSON.stringify({
        users: {}, // create in data source
      }),
    };
  }

  // continue similar implementation for update and delete...

}

export default async (event, context) => {
  return await new UsersController().handle(event, context);
};

Note: You can setup the directories and file name to whatever you like just make sure to update the serverless.yml handler

Develop Offline

By installing serverless-offline it allows you test out the code locally

$ serverless offline start --dontPrintOutput

Deploying

Serverless Webpack bundles the project for serverless. If you want to include/exclude specific node packages you can do that in the serverless.yml configuration for serverless-webpack.

$ serverless deploy

Conclusion

In this tutorial you learned how to:

  • Implement Services Pattern
  • Configure Serverless Framework
  • Configure Webpack
  • Develop Offline
  • Deploy

If you would like to see a working example you can check out this directory in my node-learning repository.

Lets chat on Twitter

Leave a comment by replying this tweet.