Skip to content

Instantly share code, notes, and snippets.

@proton0210
Created June 14, 2024 13:45
Show Gist options
  • Save proton0210/786f65ae98430f0823a732eeea4c2619 to your computer and use it in GitHub Desktop.
Save proton0210/786f65ae98430f0823a732eeea4c2619 to your computer and use it in GitHub Desktop.
sf-UploadFile
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { ulid } from "ulid";
const dynamoDBClient = new DynamoDBClient({});
const s3Client = new S3Client({});
export const handler = async (event: {
body: string;
}): Promise<{ statusCode: number; body: string; headers: unknown }> => {
const id = ulid();
const tableName = process.env.TABLE_NAME;
const bucketName = process.env.BUCKET_NAME;
if (tableName === undefined || bucketName === undefined) {
throw new Error("Missing environment variable");
}
try {
// First parse the body to get the actual JSON string
const firstParsedBody = JSON.parse(event.body.trim());
console.log("First parsed body", firstParsedBody);
// Then parse the actual JSON string to get the object
const parsedBody = JSON.parse(firstParsedBody);
console.log("Second parsed body", parsedBody);
const userId = parsedBody.userId;
const fileName = parsedBody.fileName;
const name = parsedBody.name;
const quantity = parsedBody.quantity;
// Console log the userId, fileName, and name
console.log("userId", userId);
console.log("fileName", fileName);
console.log("name", name);
if (
userId === undefined ||
fileName === undefined ||
name === undefined ||
quantity === undefined
) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Missing userId, fileName, name, or quantity",
}),
headers: {
"Access-Control-Allow-Origin": "*",
},
};
}
await dynamoDBClient.send(
new PutItemCommand({
TableName: tableName,
Item: {
ProductID: { S: id },
Name: { S: name },
stock: { N: quantity.toString() },
createdBy: { S: userId },
ImageName: { S: fileName },
},
})
);
const uploadUrl = await getSignedUrl(
s3Client,
new PutObjectCommand({
Bucket: bucketName,
Key: `${fileName}`,
}),
{ expiresIn: 60 }
);
return {
statusCode: 200,
body: JSON.stringify({ uploadUrl }),
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,PUT",
},
};
} catch (error) {
console.error("Error processing request:", error);
return {
statusCode: 400,
body: JSON.stringify({ message: "Invalid request body" }),
headers: {
"Access-Control-Allow-Origin": "*",
},
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment