-
-
Save yogesh-xseed/529b3bbd25ac732951601c92daac9b5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment