Connecting Cloud Infrastructure (AWS)
Constructing and tying together your cloud infrastructure with generative AI like ChatGPT
Summary
Prompt
Provide an example of how to connect an API Gateway to an AWS Lambda function running an Express Node.js app, which interacts with a DynamoDB table and an S3 bucket in the context of a bicycle rental application.Response
// Required dependencies: aws-sdk, aws-serverless-express
const AWS = require('aws-sdk');
const express = require('express');
const serverless = require('aws-serverless-express');
const { v4: uuidv4 } = require('uuid');
const app = express();
app.use(express.json());
const s3 = new AWS.S3();
const dynamodb = new AWS.DynamoDB.DocumentClient();
const BUCKET_NAME = process.env.BUCKET_NAME;
const TABLE_NAME = process.env.TABLE_NAME;
// Upload bicycle image to S3
app.post('/bicycle-image', async (req, res) => {
const imageBuffer = Buffer.from(req.body.image, 'base64');
const key = uuidv4() + '.png';
const params = {
Bucket: BUCKET_NAME,
Key: key,
Body: imageBuffer,
ContentType: 'image/png',
};
try {
await s3.upload(params).promise();
res.json({ imageUrl: `https://${BUCKET_NAME}.s3.amazonaws.com/${key}` });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Add bicycle to DynamoDB
app.post('/bicycle', async (req, res) => {
const bicycle = req.body;
const params = {
TableName: TABLE_NAME,
Item: bicycle,
};
try {
await dynamodb.put(params).promise();
res.json({ message: 'Bicycle added successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get bicycles from DynamoDB
app.get('/bicycles', async (req, res) => {
const params = {
TableName: TABLE_NAME,
};
try {
const result = await dynamodb.scan(params).promise();
res.json(result.Items);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const server = serverless.createServer(app);
exports.handler = (event, context) => {
serverless.proxy(server, event, context);
};Discussion
Last updated