Leo
Â
Dev at TURBINE XBERG
function holds all information that it needs to execute
states -> db
$ npm install -g serverless
service: my-app
provider:
name: aws
runtime: nodejs6.10
stage: dev
region: eu-central-1
functions:
homePage:
handler: src/homePage.handler
events:
- http: 'GET /'
'use strict';
module.exports.handler = (event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'Welcome to my website',
input: event,
}),
};
callback(null, response);
};
serverless.yml
service: my-app
provider:
...
environment:
DYNAMODB_LOG_TABLE: ${self:service}-request-log-${self:provider.stage}
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:PutItem
Resource: "arn:aws:dynamodb:${self:provider.region}:*:table/${self:provider.environment.DYNAMODB_LOG_TABLE}"
...
serverless.yml
Â
resources:
Resources:
RequestLogDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
Properties:
AttributeDefinitions:
-
AttributeName: id
AttributeType: S
KeySchema:
-
AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:provider.environment.DYNAMODB_LOG_TABLE}
const uuid = require('uuid');
const aws = require('aws-sdk');
const dynamoDb = new aws.DynamoDB.DocumentClient();
module.exports.handler = (event, context, callback) => {
...
const params = {
TableName: process.env.DYNAMODB_LOG_TABLE,
Item: {
id: uuid.v1(),
function: 'homePage.handler',
requestTime: new Date().getTime()
},
};
dynamoDb.put(params, (error) => {
if(error) {
// we should do some error handling ...
console.log(error);
}
callback(null, response);
}
};
# install plugins
$ npm install serverless-offline --save-dev
$ npm install serverless-dynamodb-local --save-dev
# add plugins to serverless.yml
# start offline server
$ sls dynamodb install
$ sls dynamodb start --migrate
$ sls offline start
$ sls invoke local -f homePage
create app
$ sls create --template aws-nodejs --path my-app
deploy app
$ sls deploy
deploy single function
$ sls deploy -f my-function
run function
$ sls invoke -f my-function
see live logs like tail -f
$ sls logs -f my-function -t
remove everything
$ sls remove
serverless examples:
https://github.com/serverless/examples
Â
serverless official:
https://serverless.com