diff --git a/lib/stripe.js b/lib/stripe.js index 9cefc1e77b..9c4966a39c 100644 --- a/lib/stripe.js +++ b/lib/stripe.js @@ -142,6 +142,18 @@ Stripe.createNodeHttpClient = (agent) => { return new NodeHttpClient(agent); }; +/** + * Creates an HTTP client for issuing Stripe API requests which uses the Web + * Fetch API. + * + * A fetch function can optionally be passed in as a parameter. If none is + * passed, will default to the default `fetch` function in the global scope. + */ +Stripe.createFetchHttpClient = (fetchFn) => { + const {FetchHttpClient} = require('./net/FetchHttpClient'); + return new FetchHttpClient(fetchFn); +}; + Stripe.prototype = { /** * @deprecated will be removed in a future major version. Use the config object instead: diff --git a/types/net/net.d.ts b/types/net/net.d.ts index c399f4c63d..4eb43ecb4a 100644 --- a/types/net/net.d.ts +++ b/types/net/net.d.ts @@ -1,4 +1,5 @@ /// +/// import {IncomingMessage} from 'http'; declare module 'stripe' { @@ -61,5 +62,21 @@ declare module 'stripe' { ) => HttpClient< HttpClientResponse >; + + /** + * Creates an HTTP client for issuing Stripe API requests which uses the Web + * Fetch API. + * + * A fetch function can optionally be passed in as a parameter. If none is + * passed, will default to the default `fetch` function in the global scope. + */ + export const createFetchHttpClient: ( + fetchFn?: WindowOrWorkerGlobalScope['fetch'] + ) => HttpClient< + HttpClientResponse< + ReturnType, + ReadableStream + > + >; } } diff --git a/types/test/typescriptTest.ts b/types/test/typescriptTest.ts index 591e846200..f1d92de730 100644 --- a/types/test/typescriptTest.ts +++ b/types/test/typescriptTest.ts @@ -222,3 +222,30 @@ async (): Promise => { const jsonResponse: object = await response.toJSON(); }; + +// Test FetchHttpClient request processing. +async (): Promise => { + const client = Stripe.createFetchHttpClient(window.fetch); + + const response = await client.makeRequest( + 'api.stripe.com', + '443', + '/test', + 'POST', + { + 'Stripe-Account': 'account', + 'Content-Length': 123, + }, + 'requestdata', + 'https', + 80000 + ); + + const stream: ReadableStream = response.toStream(() => { + return; + }); + + const results = await stream.getReader().read(); + + const jsonResponse: object = await response.toJSON(); +};