Skip to content

Instantly share code, notes, and snippets.

@waelio
Created June 1, 2021 20:30
Show Gist options
  • Save waelio/5aa6b42d273d55441d1c99f940ad347e to your computer and use it in GitHub Desktop.
Save waelio/5aa6b42d273d55441d1c99f940ad347e to your computer and use it in GitHub Desktop.
Get Image content from aws s3 bucket. **very expensive: cpu/ram/response time**
/* eslint-disable no-unused-vars */
const AWS = require('aws-sdk');
const client = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
apiVersion: '2006-03-01',
});
exports.Images = class Images {
constructor(options, app) {
this.options = options || {};
this.bucketParams = {
Bucket: options.bucketName,
};
return this;
}
async find(params) {
const geBucketParams = {
Bucket: this.options.bucketName,
};
const bucketContainer = await client.listObjects(geBucketParams).promise();
for (const image of bucketContainer.Contents) {
image.payload = await this.setPayload(image);
}
if (bucketContainer) {
return bucketContainer.Contents;
}
}
async setPayload(img) {
const getObjectParam = {
Bucket: this.options.bucketName,
Key: img.Key,
};
return await this.getImage(getObjectParam)
.then((img) => {
return (
`data:${img.ContentType};charset=utf-8;base64, ` +
this.encode(img.Body)
);
})
.catch((e) => {
console.log('44:e', e);
return [];
});
}
async getImage(getObjectParam) {
const data = await client.getObject(getObjectParam).promise();
return data;
}
encode(data) {
let buf = Buffer.from(data);
let base64 = buf.toString('base64');
return base64;
}
async get(id) {
const getObjectParam = {
Bucket: this.options.bucketName,
Key: id,
};
return this.getImage(getObjectParam)
.then(async (img) => {
const data =
`data:${img.ContentType};charset=utf-8;base64, ` + this.encode(img.Body);
img.payload = data;
return img;
})
.catch((e) => {
return [];
});
}
async create(data, params) {
const createParams = {
Bucket: this.options.bucketName,
Key: data.key,
Body: data.body,
Metadata: {
fileType: data.meta,
},
};
const result = await client.putObject(createParams).promise();
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment