elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

progress addon not working with Put? #225

Closed yardenxr closed 5 months ago

yardenxr commented 8 months ago

hey im using "wretch": "^2.8.0", im trying to convert my axios call into wretch and im having a problem with the progress addon.

my axios call was:

    const res = await axios.put(uploadUrl, file, {
            onUploadProgress: onprogress,
            headers: { 'Content-Type': getFileType(file) },
        })

and my wretch call looks like:

await wretch(uploadUrl)
            .addon(ProgressAddon())
            .headers({ 'Content-Type': getFileType(file) }) 
            .put(file)
            .progress((loaded, total) => {
                console.log('🚀 ~ .progress ~ loaded, total:', loaded, total)
                onprogress?.(loaded, total)
            })
            .res()

the file does get uploaded etc... but it never goes into the console log of the progress function. i tried to do it with middlewares like this and it works but i dont think this is a good implementation it just was for testing purposes...

(next) => (url, opts) => {
                    // Custom middleware to handle progress
                    const totalSize = file.size
                    let loadedSize = 0
                    const abortController = new AbortController()
                    const signal = abortController.signal
                    // Attach progress event listener
                    file.stream().pipeTo(
                        new WritableStream({
                            write: (chunk) => {
                                loadedSize += chunk.length
                                onprogress?.(loadedSize, totalSize)
                            },
                        }),
                        { signal }
                    )
                    return next(url, { ...opts, signal })
                },

am i missing something? is it a bug?

elbywan commented 6 months ago

Hey @yardenxr,

am i missing something? is it a bug?

The progress addon only handles download progress.

i tried to do it with middlewares like this and it works but i dont think this is a good implementation it just was for testing purposes...

As of today there is no easy way to handle progress with fetch unfortunately. For what it's worth, I think your middleware implementation is fine, I would just add a way to pass the content length from the outside instead of relying on the file.