Serverless With NodeJS and ClaudiaJS

6 November 2017

Intro

ClaudiaJS adalah library JavaScript dan NodeJS untuk memudahkan kita dalam proses deployment ke AWS Lambda dan API Gateway . Dengan Claudia, kita dapat menggunakan Lambda microservices dengan mudah dan lebih mudah di maintain.

Slide: https://www.slideshare.net/rizafahmi/aws-lambda-with-claudiajs

GitHub Repo: https://github.com/rizafahmi/claudia-ice-cream

Walkthrough

Setup Credentials

$ vim ~/.aws/credentials

Install Claudia

$ npm install -g claudia

Write our service

$ mkdir claudia-icecream-shop
$ cd claudia-icecream-shop
$ npm init
$ npm install aws-sdk claudia-api-builder
$ vim index.js
const ApiBuilder = require('claudia-api-builder')
const AWS = require('aws-sdk')
const api = new ApiBuilder()
const dynamoDb = new AWS.DynamoDB.DocumentClient()

const TABLENAME = 'icecreams'

api.post('/icecreams',
  request => {
    const params = {
      TableName: TABLENAME,
      Item: {
        icecreamid: request.body.id,
        name: request.body.name
      }
    }
    return dynamoDb.put(params).promise()
  },
  { success: 201 }
)

api.get('/icecreams', request => {
  return dynamoDb
    .scan({ TableName: TABLENAME })
    .promise()
    .then(response => response.Items)
})

module.exports = api

Setup DynamoDB

$ aws dynamodb create-table --table-name icecreams --attribute-definition AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 --region ap-southeast-1 --query TableDescription.TableArn --output text
$ mkdir policy
$ vim policy/dynamodb-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "dynamodb:DeleteItem",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Scan"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

Deploy

$ claudia create --region ap-southeast-1 --api-module index --policies policy

Testing

$ curl -H "Content-Type: application/json" -X POST -d ‘{"id":"123","name":"chocolate"}' 
$ curl https://y667r05jii.execute-api.ap-southeast-1.amazonaws.com/latest/icecreams

Update

$ npm install uuid
const ApiBuilder = require('claudia-api-builder')
const AWS = require('aws-sdk')
const api = new ApiBuilder()
const dynamoDb = new AWS.DynamoDB.DocumentClient()
::const uuid = require('uuid/v4')::

const TABLENAME = 'icecreams'

api.post(
  '/icecreams',
  request => {
    const params = {
      TableName: TABLENAME,
      ::Item: {::
        ::icecreamid: uuid(),::
        ::name: request.body.name::
      ::}::
    }
    return dynamoDb.put(params).promise()
  },
  { success: 201 }
)

api.get('/icecreams', request => {
  return dynamoDb
    .scan({ TableName: TABLENAME })
    .promise()
    .then(response => response.Items)
})

module.exports = api
$ claudia update

Sharing is caring magic!