Lambda

I believe in learn by doing these days. In order to create a real world node.js application. I decided to go through most key features of node by creating a bunch of aws nodejs serverless lambda functions as a warm-up.

Lambda and Node, one stone two bird.

Here comes the every steps...

Serverless.com

Let's start with serverlessopen in new window, a framework that shows up a lot at egghead.

As to me I think it make sense to maintain the serverless function in serverless way. Just in case one day I will move it from aws to other cloud provider.

  • Template

You can start with a template as boilerplate by command line.

serverless create -t [template name] -p [service name]

However I have to begin with examplesopen in new window due to some annoying issue that my default local serverless provider issue. 😡

Step 1: A json crud service

  • Firstly I want to create a service that I could CRUD a json object. Based on which a number of biz api shall be built.

    So we have 2 todos as below.

  • Start with aws-node-fetch-file-and-store-in-s3open in new window template

    • give it a test and it works like a charm

    TIP

    You have to create a s3 bucket beforehand and update yml file accordingly

    custom:
      bucket: [bucket name]
    

    also IAM Role Permission have to be put in the config file either.

    provider:
      name: aws
      runtime: nodejs14.x
      stage: dev
      iam:
        role:
          statements:
            - Effect: Allow
              Action:
                - s3:GetObject
                - s3:GetObjectAcl
                - s3:PutObject
                - s3:PutObjectAcl
              Resource: "arn:aws:s3:::${self:custom.bucket}/*"
    
  • The crud service

    I don't want to use any database yet since learning Node is why all it happens in the first place. A Json file hold on the entire application data should suffice. I assumed.

    Besides I don't want to reinvent the wheel. After awhile I found this nice JSON database lib.

    lowdb only support ESM, so I have to alter the template accordingly. Pls refer to source codeopen in new window

    • adaptor

    There is no built-in s3 adaptor expect for 3rd party one lowdb-adapter-aws-s3open in new window.

    I dived into the source code and found out that it may not meed my requirement sooner or later. So I decided to create it on my own.

    see the source code of s3Adaptor.js open in new window