smartjimp/ts/smartjimp.classes.smartjimp.ts

74 lines
2.3 KiB
TypeScript
Raw Normal View History

2023-01-09 17:17:33 +00:00
import * as plugins from './smartjimp.plugins.js';
2023-12-03 17:10:35 +00:00
export interface IAssetVariation {
format?: 'avif' | 'webp' | 'png';
2023-01-09 17:17:33 +00:00
width?: number;
height?: number;
}
2020-02-02 20:10:42 +00:00
export class SmartJimp {
2023-01-09 17:17:33 +00:00
public levelCache = new plugins.levelcache.LevelCache({
cacheId: 'mastercache',
maxMemoryStorageInMB: 100,
maxDiskStorageInMB: 5000,
});
/**
* get a key that is unique for a wanted asset variation
*/
private getCacheKey(
2023-11-24 19:08:48 +00:00
sourceTypeArg: 'streamfile' | 'smartfile',
2023-01-09 17:17:33 +00:00
sourceIdArg: string,
2023-12-03 17:10:35 +00:00
assetVariationArg?: IAssetVariation
2023-01-09 17:17:33 +00:00
) {
return `${sourceTypeArg}_${sourceIdArg}_${
2023-12-03 17:10:35 +00:00
assetVariationArg
? `${assetVariationArg.width || 'auto' }x${assetVariationArg.height || 'auto'}`
2023-01-09 17:17:33 +00:00
: 'original'
}`;
}
2023-12-03 17:10:35 +00:00
public async computeAssetVariation(assetBufferArg: Buffer, assetVariationArg?: IAssetVariation) {
if (!assetVariationArg) {
return assetBufferArg;
2023-01-09 17:17:33 +00:00
}
2023-12-03 17:10:35 +00:00
let sharpImage = plugins.sharp(assetBufferArg);
sharpImage = sharpImage.resize(assetVariationArg.width, assetVariationArg.height);
const resultResize = sharpImage.resize(assetVariationArg.width, assetVariationArg.height);
switch (assetVariationArg.format) {
case 'avif':
sharpImage = resultResize.avif();
case 'webp':
sharpImage = resultResize.webp();
case 'png':
sharpImage = resultResize.png();
}
return sharpImage.toBuffer();
2023-01-09 17:17:33 +00:00
}
public async getFromSmartfile(
2023-11-24 19:08:48 +00:00
smartfileArg: plugins.smartfile.SmartFile,
2023-12-03 17:10:35 +00:00
wantedDimensionsArg?: IAssetVariation
2023-01-09 17:17:33 +00:00
) {
2023-11-24 19:08:48 +00:00
const cacheKey = this.getCacheKey('smartfile', await smartfileArg.getHash(), wantedDimensionsArg);
2023-01-09 17:17:33 +00:00
const existingCacheEntry = await this.levelCache.retrieveCacheEntryByKey(cacheKey);
if (existingCacheEntry) {
return existingCacheEntry.contents;
} else {
const computedAssetBuffer = await this.computeAssetVariation(smartfileArg.contentBuffer, wantedDimensionsArg);
this.levelCache.storeCacheEntryByKey(cacheKey, new plugins.levelcache.CacheEntry({
contents: computedAssetBuffer,
ttl: 600000
}));
return computedAssetBuffer;
}
}
2023-11-24 19:08:48 +00:00
public async createAvifImageFromBuffer(bufferArg: Buffer) {
const sharpImage = plugins.sharp(bufferArg);
const result = await sharpImage.avif().toBuffer();
return result;
}
2020-02-02 20:10:42 +00:00
}