smartjimp/ts/smartjimp.classes.smartjimp.ts
2023-12-03 18:10:35 +01:00

74 lines
2.3 KiB
TypeScript

import * as plugins from './smartjimp.plugins.js';
export interface IAssetVariation {
format?: 'avif' | 'webp' | 'png';
width?: number;
height?: number;
}
export class SmartJimp {
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(
sourceTypeArg: 'streamfile' | 'smartfile',
sourceIdArg: string,
assetVariationArg?: IAssetVariation
) {
return `${sourceTypeArg}_${sourceIdArg}_${
assetVariationArg
? `${assetVariationArg.width || 'auto' }x${assetVariationArg.height || 'auto'}`
: 'original'
}`;
}
public async computeAssetVariation(assetBufferArg: Buffer, assetVariationArg?: IAssetVariation) {
if (!assetVariationArg) {
return assetBufferArg;
}
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();
}
public async getFromSmartfile(
smartfileArg: plugins.smartfile.SmartFile,
wantedDimensionsArg?: IAssetVariation
) {
const cacheKey = this.getCacheKey('smartfile', await smartfileArg.getHash(), wantedDimensionsArg);
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;
}
}
public async createAvifImageFromBuffer(bufferArg: Buffer) {
const sharpImage = plugins.sharp(bufferArg);
const result = await sharpImage.avif().toBuffer();
return result;
}
}