Browse Source

enable CORS for global access, and remove temp files and add logging

pull/1/head
Trent Larson 9 months ago
parent
commit
0d7020daf7
  1. 10
      README.md
  2. 1
      package.json
  3. 11
      pnpm-lock.yaml
  4. 26
      server.js

10
README.md

@ -5,7 +5,15 @@
```
sh <(curl https://pkgx.sh) +pnpm sh
pnpm install
# manually set the AWS_ variables inside the .env file
# create the directory for files that are being uploaded; should stay empty afterward
mkdir uploads
```
Now manually set these AWS_ variables inside a .env file:
```
AWS_ACCESS_KEY=
AWS_SECRET_KEY=
AWS_REGION=
```
## dev

1
package.json

@ -6,6 +6,7 @@
"dependencies": {
"@aws-sdk/client-s3": "^3.521.0",
"@aws-sdk/lib-storage": "^3.521.0",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"multer": "1.4.5-lts.1"

11
pnpm-lock.yaml

@ -11,6 +11,9 @@ dependencies:
'@aws-sdk/lib-storage':
specifier: ^3.521.0
version: 3.521.0(@aws-sdk/client-s3@3.521.0)
cors:
specifier: ^2.8.5
version: 2.8.5
dotenv:
specifier: ^16.4.5
version: 16.4.5
@ -1238,6 +1241,14 @@ packages:
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
dev: false
/cors@2.8.5:
resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==}
engines: {node: '>= 0.10'}
dependencies:
object-assign: 4.1.1
vary: 1.1.2
dev: false
/debug@2.6.9:
resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==}
peerDependencies:

26
server.js

@ -1,4 +1,5 @@
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const cors = require('cors');
const crypto = require('crypto');
const express = require('express');
const fs = require('fs');
@ -7,6 +8,8 @@ const path = require('path');
require('dotenv').config()
const app = express();
app.use(cors());
const port = 3000;
// Configure AWS
@ -33,7 +36,8 @@ app.post('/image', upload.single('image'), (req, res) => {
const hashHex = hashSum.digest('hex');
const bucketName = 'gifts-image';
const fileName = `${hashHex}_${file.originalname}`;
console.log(file.originalname, '=>', file.path, '=>', hashHex);
const fileName = hashHex;
const params = {
Body: data,
Bucket: bucketName, // S3 Bucket name
@ -45,11 +49,23 @@ app.post('/image', upload.single('image'), (req, res) => {
try {
const command = new PutObjectCommand(params);
const response = await s3Client.send(command);
const finalUrl = `https://${bucketName}.s3.amazonaws.com/${fileName}`;
res.send(JSON.stringify({ success: true, url: finalUrl }));
if (response.$metadata.httpStatusCode !== 200) {
const errorTime = new Date().toISOString();
console.log(errorTime, "Error uploading to S3 with bad HTTP status. Metadata:", response.$metadata);
res.status(500).send(JSON.stringify({ success: false, message: "Got bad status of " + response.$metadata.httpStatusCode + " from AWS. See server logs at " + errorTime }));
} else {
const finalUrl = `https://${bucketName}.s3.amazonaws.com/${fileName}`;
fs.rm(file.path, (err) => {
if (err) {
console.error("Error deleting temp file", file.path, "with error:", err);
}
});
res.send(JSON.stringify({ success: true, url: finalUrl }));
}
} catch (uploadError) {
console.error('Error uploading to S3:', uploadError);
res.status(500).send(JSON.stringify({ success: false, message: 'Error uploading file.' }));
const errorTime = new Date().toISOString();
console.error(errorTime, "Error uploading to S3:", uploadError);
res.status(500).send(JSON.stringify({ success: false, message: "Got error uploading file. See server logs at " + errorTime + " Error Details: " + JSON.stringify(uploadError) }));
}
});
});

Loading…
Cancel
Save