Skip to content

Instantly share code, notes, and snippets.

@marlenesco
Last active August 9, 2023 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlenesco/09b4a0aaef66384ea0afbc2100738501 to your computer and use it in GitHub Desktop.
Save marlenesco/09b4a0aaef66384ea0afbc2100738501 to your computer and use it in GitHub Desktop.
Storage class for aws-sdk v3, use it in node adn serverless app
// locate the storage class in your application
const storage = require('../path-to/storage');
module.exports = async (body, key) => {
try {
//using that class to put object in s3
await storage.put(
process.env.ASSETS_BUCKET,
key,
body,
{
"content-type": "whatever/you-want"
}
);
return true;
} catch (error) {
console.log(error.message);
return false;
}
};
const { S3Client, GetObjectCommand, PutObjectCommand, ListObjectsV2Command, HeadObjectCommand, DeleteObjectCommand } = require("@aws-sdk/client-s3");
class Storage {
constructor() {
let params = {};
if (process.env.STAGE === 'dev') {
params = {
forcePathStyle: true,
credentials: {
accessKeyId: "S3RVER",
secretAccessKey: "S3RVER",
},
endpoint: process.env.S3_ENDPOINT,
}
}
this.client = new S3Client(params);
}
async get(bucketName, filename) {
return this.client.send(
new GetObjectCommand({
Bucket: bucketName,
Key: filename,
})
);
}
async put(bucketName, filename, buffer, metadata = undefined) {
return this.client.send(
new PutObjectCommand({
Bucket: bucketName,
Key: filename,
Body: buffer,
Metadata: metadata || {}
})
);
}
async list(bucketName, prefix= undefined, nextToken = undefined) {
return this.client.send(
new ListObjectsV2Command({
Bucket: bucketName,
Prefix: prefix,
ContinuationToken: nextToken
})
);
}
async exists(bucketName, filename) {
try {
await this.client.send(
new HeadObjectCommand({
Bucket: bucketName,
Key: filename,
})
);
return true;
} catch (error) {
if (error.statusCode === 404) {
return false;
}
throw error;
}
}
async delete(bucketName, filename) {
return this.client.send(
new DeleteObjectCommand({
Bucket: bucketName,
Key: filename,
})
);
}
}
const singletonInstance = new Storage();
module.exports = Object.freeze(singletonInstance);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment