Configurando el iamRoleStatements del recurso podemos conectarnos a el.
# Serverless.yml
service: aws-lambda-crud-node
frameworkVersion: '2 || 3'
provider:
name: aws
runtime: nodejs12.x
lambdaHashingVersion: '20201221'
region: us-west-2
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:*
Resource:
- arn:aws:dynamodb:us-west-2:xxxxxxxxx:table/TaskTable
functions:
resources:
Esto crea una nueva tabla con un id como partition key de tipo string.
resources:
Resources:
TaskTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: TaskTable
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
keyType: HASH
// addTask.js
const { v4 } = require('uuid')
const AWS = require('aws-sdk')
const addTask = async(event) => {
// Conectar a la base de datos, mediante el clientID
const dynamodb = new AWS.DynamoDB.DocumentClient()
const { title, description } = JSON.parse(event.body)
const createdAt = new Date()
const id = v4()
const newTask = {
id,
title,
description,
createdAt
}
await dynamodb.put({
TableName: 'TaskTable',
Item: newTask
}).promise()
return {
statusCode: 200,
body: JSON.stringify(newTask)
}
}
module.exports = {
addTask,
}
functions:
createTask:
handler: src/addTask.addTask
events:
- httpApi:
path: /tasks
method: post
sls deploy --verbose