Skip to content

Instantly share code, notes, and snippets.

@benawad
Created April 7, 2019 23:29
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 18 You must be signed in to fork a gist
  • Save benawad/22090ba1fe341f3491fd34d17970beb8 to your computer and use it in GitHub Desktop.
Save benawad/22090ba1fe341f3491fd34d17970beb8 to your computer and use it in GitHub Desktop.
import * as Sentry from "@sentry/node";
import imagemin from "imagemin";
import mozjpeg from "imagemin-mozjpeg";
import sharp from "sharp";
import isJpg from "is-jpg";
import * as aws from "aws-sdk";
import { Upload } from "../../types/graphqlUtils";
import { generateFilename } from "./generateFilename";
export const s3 = new aws.S3({
signatureVersion: "v4",
region: "us-east-1"
});
const convertToJpg = async (input: Buffer) => {
if (isJpg(input)) {
return input;
}
return sharp(input)
.jpeg()
.toBuffer();
};
export const uploadBuffer = async (buffer: Buffer) => {
const miniBuffer = await imagemin.buffer(buffer, {
plugins: [convertToJpg, mozjpeg({ quality: 85 })]
});
const Key = generateFilename();
await s3
.upload({
Bucket: process.env.S3_BUCKET as string,
Key,
Body: miniBuffer
})
.promise();
return Key;
};
export const uploadImageStream = async (picture: Promise<Upload>) => {
const buffers: Uint8Array[] = [];
const readableStream = await picture;
const buffer = await new Promise<Buffer | null>(async res =>
readableStream
.createReadStream()
.on("data", chunk => {
buffers.push(chunk);
})
.on("end", () => {
res(Buffer.concat(buffers));
})
.on("error", err => {
Sentry.captureException(err);
res(null);
})
);
if (!buffer) {
return null;
}
return uploadBuffer(buffer);
};
@ibadeeCodes
Copy link

It was helpful. Thanks Ben

@abhilashrathod
Copy link

Thank you Ben!

@2donny
Copy link

2donny commented Nov 10, 2021

Thanks Ben!

@J-Zam
Copy link

J-Zam commented Jan 24, 2022

Gracias Bro 💯

@afeef-rb
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment