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 serverless, 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 examples 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.
- a serverless function CRUD a javascript object.
- a S3 bucket hold on the json file.
Start with aws-node-fetch-file-and-store-in-s3 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}/*"
- refer to commit
The
crud
serviceI 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 code- adaptor
There is no built-in
s3 adaptor
expect for 3rd party one lowdb-adapter-aws-s3.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