Reputation: 13
on node.js using sharp library how can we add condition in the chaining condition i try using this. is that possible to do that??
S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
if(useCrop){
.crop(width, height)
}
if(useResize){
.resize(width, height)
}
.toFormat(setFormat)
.withoutEnlargement(p_withoutEnlargement)
.quality(quality)
.max(max)
.flatten()
.toBuffer()
)
.then(buffer => S3.putObject({
Body: buffer,
Bucket: BUCKET,
ContentType: 'image/'+setFormat,
CacheControl: `max-age=${maxAge}`,
Key: key,
}).promise()
)
.then(() => callback(null, {
statusCode: '301',
headers: {'location': `${URL}/${key}`},
body: '',
})
)
Upvotes: 0
Views: 160
Reputation: 664620
Just use a temporary variable:
.then(data => {
let s = Sharp(data.Body);
if(useCrop){
s = s.crop(width, height)
}
if(useResize){
s = s.resize(width, height)
}
return s.toFormat(setFormat)
.withoutEnlargement(p_withoutEnlargement)
.quality(quality)
.max(max)
.flatten()
.toBuffer();
})
You can also do without mutation:
const orig = Sharp(data.Body);
const withPossibleCrop = useCrop ? orig.crop(width, height) : orig;
const withPossibleCropAndResize = useResize ? withPossibleCrop.resize(width, height) : withPossibleCrop;
return withPossibleCropAndResize.toFormat(…).…;
Upvotes: 2