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

Commit

Permalink
feat(wip): use sharp to genrate webp and avif
Browse files Browse the repository at this point in the history
  • Loading branch information
YanceyOfficial committed Sep 26, 2021
1 parent a3eb0aa commit b569e0e
Show file tree
Hide file tree
Showing 3 changed files with 204 additions and 7 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"request-ip": "^2.1.3",
"rxjs": "^6.6.7",
"serve-favicon": "^2.5.0",
"sharp": "^0.29.1",
"speakeasy": "^2.0.0",
"ua-parser-js": "^0.7.28",
"uuid": "^8.3.2",
Expand All @@ -88,6 +89,7 @@
"@types/ramda": "^0.27.44",
"@types/request-ip": "^0.0.35",
"@types/serve-favicon": "^2.5.2",
"@types/sharp": "^0.29.2",
"@types/speakeasy": "^2.0.5",
"@types/supertest": "^2.0.10",
"@types/ua-parser-js": "^0.7.35",
Expand Down
25 changes: 24 additions & 1 deletion src/uploaders/uploaders.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common'
import { FileUpload } from 'graphql-upload'
import { BlobServiceClient, ContainerClient } from '@azure/storage-blob'
import { randomSeries, getFileExtension } from 'yancey-js-util'
import sharp from 'sharp'
import { ConfigService } from '../config/config.service'
import { AZURE_STORAGE_URL, AZURE_STORAGE_CONTAINER_NAME } from '../shared/constants'

Expand All @@ -17,6 +18,16 @@ export class UploadersService {
this.containerClient = blobServiceClient.getContainerClient(AZURE_STORAGE_CONTAINER_NAME)
}

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

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

public async uploadFile(file: FileUpload) {
const { createReadStream, filename } = file
const rs = createReadStream()
Expand All @@ -33,12 +44,24 @@ export class UploadersService {
const blockBlobClient = this.containerClient.getBlockBlobClient(blobName)
const { errorCode } = await blockBlobClient.upload(buffer, Buffer.byteLength(buffer))

const webp = await this.convertImageToWebp(buffer)
const { errorCode: webpErrorCode } = await blockBlobClient.upload(
webp,
Buffer.byteLength(webp),
)

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

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

if (errorCode) {
if (errorCode || webpErrorCode || avifErrorCode) {
reject(errorCode)
} else {
// @ts-ignore
Expand Down
Loading

0 comments on commit b569e0e

Please sign in to comment.