Add webp thumbnail conversion task to optimize performance of fast scrolling (#172)

* Update readme

* Added webp to table and entity

* Added cronjob and sharp dependencies

* Added conversion of webp every 5 minutes and endpoint will now server webp image if exist
This commit is contained in:
Alex
2022-05-22 06:56:36 -05:00
committed by GitHub
parent ce06af0c9b
commit 55c5027539
11 changed files with 731 additions and 21 deletions

View File

@@ -0,0 +1,52 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AssetEntity } from '../../api-v1/asset/entities/asset.entity';
import sharp from 'sharp';
@Injectable()
export class ImageConversionService {
constructor(
@InjectRepository(AssetEntity)
private assetRepository: Repository<AssetEntity>
) { }
@Cron(CronExpression.EVERY_5_MINUTES
, {
name: 'webp-conversion'
})
async webpConversion() {
Logger.log('Starting Webp Conversion Tasks', 'ImageConversionService')
const assets = await this.assetRepository.find({
where: {
webpPath: ''
},
take: 500
});
if (assets.length == 0) {
Logger.log('All assets has webp file - aborting task', 'ImageConversionService')
return;
}
for (const asset of assets) {
const resizePath = asset.resizePath;
if (resizePath != '') {
const webpPath = resizePath.replace('jpeg', 'webp')
sharp(resizePath).resize(250).webp().toFile(webpPath, (err, info) => {
if (!err) {
this.assetRepository.update({ id: asset.id }, { webpPath: webpPath })
}
});
}
}
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AssetEntity } from '../../api-v1/asset/entities/asset.entity';
import { ImageConversionService } from './image-conversion.service';
@Module({
imports: [
TypeOrmModule.forFeature([AssetEntity]),
],
providers: [ImageConversionService],
})
export class ScheduleTasksModule { }