Hi,
I'm using Sharp for compressing uploaded user images. I want to be sure that my approach is safe and performs in theory for all cases.
I'm rather hesitant, as I didn't set proper testing yet and for now I didn't deploy the app but doing big refactoring on the code then I will test everything the next days.
I am hesitant if my code is correct, and would like to hear from you also about it. Here it is:
const width_ = 200
try {
thumbnailBuffer = await sharp(originalBuffer)
.metadata()
.then(({ width }) => {
if(width > 400) {
return sharp(originalBuffer)
.resize(Math.round(width * 0.5)).toBuffer()
} else if(width > 200){
return sharp(originalBuffer)
.resize(width_, { fit: 'inside' }).toBuffer()
} else {
return undefined
}
})
} catch (error) {
req.log.error(`post/listings#postListingHandler#sharp: ${error.message}`)
}
Will thumbnailBuffer
contain a value of a new buffer or a promise or this whole thing is incorrect ?
Thanks a lot !!
Top comments (5)
I've taken the code and modified it slightly. Like this, it seemed a bit easier to understand for me:
The type of value this function returns is
Promise<any>
. More specifically:undefined
is returned inside a PromiseA hint of advice: If you're using VSCode, you can add the following line to you config file to enable simple type checks for Javascript:
"js/ts.implicitProjectConfig.checkJs": true,
Thanks a lot @tqbit I will take a look on the extension as well.
I found some examples in gists so I will write proper tests and experience with this.
As far as I can tell, without knowing the sharp API at all, it seems that thumbnailBuffer will be a buffer is the width is greater that 200, otherwise it will be undefined.
Yes that what I intended to writing the code. But I meant JavaScript language speaking, does the return inside then return the value (here buffer/undefined) or a promise or go to heat...
It should be the value, as you're using async/await.