Skip to content

Instantly share code, notes, and snippets.

@w0rldart
Last active May 20, 2023 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w0rldart/933cea5a12baa835e69ae68d2de7117c to your computer and use it in GitHub Desktop.
Save w0rldart/933cea5a12baa835e69ae68d2de7117c to your computer and use it in GitHub Desktop.
NodeJS Lambda with DynamoDB setup for dev environment
const AWS = require('aws-sdk')
const IS_OFFLINE = process.env.NODE_ENV !== 'production'
let options = {}
// connect to local DB if running offline
if (IS_OFFLINE) {
const DYNAMO_ENDPOINT = process.env.DYNAMO_ENDPOINT
options = {
region: 'localhost',
endpoint: DYNAMO_ENDPOINT,
accessKeyId: 'DEFAULT_ACCESS_KEY',
secretAccessKey: 'DEFAULT_SECRET'
}
}
const dynamoDb = new AWS.DynamoDB.DocumentClient(options)
dynamoDb.scan(params, (error, result) => {
if (error) {
return { error: 'Error fetching notifications' }
}
return result.Items
})
version: "3"
services:
dynamo:
image: "amazon/dynamodb-local:latest"
command: ["-jar", "DynamoDBLocal.jar", "-sharedDb", "-inMemory"]
ports:
- "8000:8000"
lambda:
image: "node:10-alpine"
user: node
working_dir: /home/node/app
command: npm run dev
environment:
DYNAMO_ENDPOINT: http://dynamo:8000
# Note: even though these keys are garbage values, access key and
# secret key are still required. Otherwise, `aws-sdk` will attempt
# to read credentials from Amazon's `169.254.169.254` service and
# fail.
AWS_ACCESS_KEY_ID: "abc"
AWS_SECRET_ACCESS_KEY: "xyz"
AWS_REGION: "us-east-1"
depends_on:
- dynamo
volumes:
- .:/home/node/app
ports:
- "3000:3000"
"scripts": {
"dev": "nodemon local.js"
},
#!/bin/bash
set -e
# Launch docker containers
docker-compose up -d
# Create notifications table
aws dynamodb create-table --cli-input-json file://table-model.json --endpoint-url http://localhost:8000
{
"TableName": "notifications",
"KeySchema": [
{
"AttributeName": "id",
"KeyType": "HASH"
}
],
"AttributeDefinitions": [
{
"AttributeName": "id",
"AttributeType": "S"
}
],
"ProvisionedThroughput": {
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
}
}
@w0rldart
Copy link
Author

Run ./start-dev.sh to get going

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment