Skip to content
This repository has been archived by the owner on Nov 29, 2021. It is now read-only.

Commit

Permalink
feat: finish sharp
Browse files Browse the repository at this point in the history
  • Loading branch information
YanceyOfficial committed Sep 26, 2021
1 parent b569e0e commit 705a48e
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions src/uploaders/uploaders.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,21 @@ export class UploadersService {
}

private async convertImageToWebp(image: Buffer) {
const buffer = await sharp(image).webp().toBuffer()
const buffer = await sharp(image).webp({ quality: 90 }).toBuffer()
return buffer
}

private async convertImageToAVIF(image: Buffer) {
const buffer = await sharp(image).avif().toBuffer()
const buffer = await sharp(image).avif({ quality: 80 }).toBuffer()
return buffer
}

private async upload(fileName: string, extension: string, buffer: Buffer) {
const blockBlobClient = this.containerClient.getBlockBlobClient(`${fileName}.${extension}`)
const { errorCode } = await blockBlobClient.upload(buffer, Buffer.byteLength(buffer))
return errorCode
}

public async uploadFile(file: FileUpload) {
const { createReadStream, filename } = file
const rs = createReadStream()
Expand All @@ -39,30 +45,30 @@ export class UploadersService {
})

rs.addListener('end', async () => {
const blobName = `${randomSeries(8)}-${+new Date()}.${getFileExtension(filename)}`
const hash = `${randomSeries(8)}-${+new Date()}`
const buffer = Buffer.concat(buffers)
const blockBlobClient = this.containerClient.getBlockBlobClient(blobName)
const { errorCode } = await blockBlobClient.upload(buffer, Buffer.byteLength(buffer))
const extension = getFileExtension(filename)
const images = ['jpeg', 'jpg', 'png', 'gif']
let webpFileError = null
let avifFileError = null

const webp = await this.convertImageToWebp(buffer)
const { errorCode: webpErrorCode } = await blockBlobClient.upload(
webp,
Buffer.byteLength(webp),
)
if (images.includes(extension.toLowerCase())) {
const webp = await this.convertImageToWebp(buffer)
const avif = await this.convertImageToAVIF(buffer)
webpFileError = await this.upload(hash, 'webp', webp)
avifFileError = await this.upload(hash, 'avif', avif)
}

const avif = await this.convertImageToWebp(buffer)
const { errorCode: avifErrorCode } = await blockBlobClient.upload(
avif,
Buffer.byteLength(avif),
)
const originFileError = await this.upload(hash, extension, buffer)

const res = {
name: filename,
url: `${AZURE_STORAGE_URL}/${AZURE_STORAGE_CONTAINER_NAME}/${blobName}`,
url: `${AZURE_STORAGE_URL}/${AZURE_STORAGE_CONTAINER_NAME}/${hash}.${extension}`,
}

if (errorCode || webpErrorCode || avifErrorCode) {
reject(errorCode)
const error = originFileError || webpFileError || avifFileError
if (error) {
reject(error)
} else {
// @ts-ignore
resolve(res)
Expand Down

0 comments on commit 705a48e

Please sign in to comment.