Skip to content

feat: support body as factory function for retryable requests#5008

Open
mcollina wants to merge 1 commit intomainfrom
feature/body-factory
Open

feat: support body as factory function for retryable requests#5008
mcollina wants to merge 1 commit intomainfrom
feature/body-factory

Conversation

@mcollina
Copy link
Copy Markdown
Member

@mcollina mcollina commented Apr 9, 2026

This implements support for passing a factory function as the body option, which creates a new body instance for each dispatch. This enables retryable requests with bodies that can be recreated, such as file streams or async generators.

Example with the retry interceptor:

const { Client, interceptors } = require('undici')
const fs = require('node:fs')

const client = new Client('http://example.com')
  .compose(interceptors.retry({
    methods: ['POST']
  }))

// Retryable POST with file body - a new stream is created for each retry
const result = await client.request({
  method: 'POST',
  path: '/upload',
  headers: { 'content-type': 'application/octet-stream' },
  body: () => fs.createReadStream('/path/to/file.txt')
})

The factory function is called once for the initial dispatch and once for each retry, ensuring a fresh body is used each time.

Refs: #112

This implements support for passing a factory function as the body option,
which creates a new body instance for each dispatch. This enables retryable
requests with bodies that can be recreated, such as file streams or async
generators.

Example:
  body: () => fs.createReadStream('file.txt')

The factory function is called once for the initial dispatch and once for
each retry, ensuring a fresh body is used each time.

Refs: #112
@codecov-commenter
Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.40506% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.95%. Comparing base (a434502) to head (713cec6).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
lib/core/util.js 91.54% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5008      +/-   ##
==========================================
+ Coverage   92.93%   92.95%   +0.01%     
==========================================
  Files         110      110              
  Lines       35735    35814      +79     
==========================================
+ Hits        33210    33290      +80     
+ Misses       2525     2524       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
Member

@ronag ronag left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but there is a different way by using an interceptor before the retry interceptor:

import { Readable } from 'node:stream'
import { isStream } from '../utils.js'

class FactoryStream extends Readable {
  #factory
  #ac
  #body

  constructor(factory) {
    super()
    this.#factory = factory
  }

  _construct(callback) {
    this.#ac = new AbortController()
    Promise.resolve(this.#factory({ signal: this.#ac.signal })).then(
      (body) => {
        this.#ac = null
        try {
          if (typeof body === 'string' || body instanceof Buffer) {
            this.push(body)
            this.push(null)
          } else if (isStream(body)) {
            this.#body = body
          } else {
            this.#body = Readable.from(body)
          }

          if (this.#body != null) {
            this.#body
              .on('data', (data) => {
                if (!this.push(data)) {
                  this.#body.pause()
                }
              })
              .on('end', () => {
                this.push(null)
              })
              .on('error', (err) => {
                this.destroy(err)
              })
          }

          callback(null)
        } catch (err) {
          callback(err)
        }
      },
      (err) => callback(err),
    )
  }

  _read() {
    this.#body?.resume()
  }

  _destroy(err, callback) {
    if (this.#ac) {
      this.#ac.abort(err)
      this.#ac = null
    }

    if (this.#body) {
      this.#body.destroy(err)
      this.#body = null
    }

    callback(err)
  }
}

export default () => (dispatch) => (opts, handler) =>
  typeof opts.body !== 'function'
    ? dispatch(opts, handler)
    : dispatch({ ...opts, body: new FactoryStream(opts.body) }, handler)

Copy link
Copy Markdown
Member

@metcoder95 metcoder95 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but wondering the use-cases; this seems pretty specific to retry interceptor; if that's the case, I believe documenting @ronag comment can be a good alternative.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants