---
# System prepended metadata

title: Serverless

---

# Serverless

```bash
Is a function responding to an API endpoint. A request comes in,
server wakes up, runs for a few ms, and go to sleep.
The platform takes care of optimization, configuration,
and everything else
```

## Key features

Easy to add new services.
Quickly gain familiarity with the project.
Don't deal with servers, focus on application code

## Components

Functions
Events: http, cron
Resources: dynamoDB, schedule, S3 changes
Service: It's like a project. It's where you define your AWS Lambda Functions, the events that trigger them and any AWS infrastructure resources they require, all in a file called serverless.yml

Use templates
`serverless create --template aws-nodejs --path servicename`
`npm init && npm -i`

## Layers

A Lambda layer is a .zip file archive that can contain additional code or data. A layer can contain libraries, a custom runtime, data, or configuration files. Layers promote code sharing and separation of responsibilities so that you can iterate faster on writing business logic.

Layers are extracted on the /opt directory of the function environment

## DynamoDB

Item: row equivalent in SQL
Attribute: column
Table: collection of items

`docker run -d -p 8001:8001 --name=dynamoDB-local amazon/dynamodb-local`
`aws dynamodb list-tables --endpoint=http://localhost:8000`

```bash
// create a simple template schema
aws dynamodb create-table --generate-cli-skeleton > dynamo_table_def.json

// create a table with a json file
aws dynamodb create-table --cli-input-json \
      file://dynamo_table_def.json \
      --endpoint-url http://localhost:port

// insert item
aws dynamodb put-item \
      --table-name Posts \
      --item '{
                "id": {"S": "1"},
                "Title": {"S": "my first title"}
                }' \
      --return-consumed-capacity TOTAL \
      --endpoint-url http://localhost:port

// list items
aws dynamodb scan --table-name TABLENAME \
  --endpoint-url http://127.0.0.1:port

```bash

# GUI client for local dynamoDB

dynamodb-admin is a gui tool to visualize and manipulate data.

```bash
//install global package
$ npm install -g dynamodb-admin

// runs gui in http://localhost:8001
$ AWS_REGION=localhost DYNAMO_ENDPOINT=http://localhost:8000 \
  dynamodb-admin
```

## Run service offline

```bash
serverless offline start
```

### Create a Post

```bash
curl -X POST -H "Content-Type:application/json" http://localhost:3000/dev/post --data '{ "title": "my awesome title", "text": "my awesome text" }'
```
