Skip to content

Commit

Permalink
Add typed createFetchHttpClient function. (#1273)
Browse files Browse the repository at this point in the history
  • Loading branch information
dcr-stripe authored Oct 18, 2021
1 parent 38300af commit 567da28
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/stripe.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
17 changes: 17 additions & 0 deletions types/net/net.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/// <reference types="node" />
/// <reference lib="dom" />

import {IncomingMessage} from 'http';
declare module 'stripe' {
Expand Down Expand Up @@ -61,5 +62,21 @@ declare module 'stripe' {
) => HttpClient<
HttpClientResponse<IncomingMessage, Stripe.StripeStreamResponse>
>;

/**
* 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<WindowOrWorkerGlobalScope['fetch']>,
ReadableStream<Uint8Array>
>
>;
}
}
27 changes: 27 additions & 0 deletions types/test/typescriptTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,30 @@ async (): Promise<void> => {

const jsonResponse: object = await response.toJSON();
};

// Test FetchHttpClient request processing.
async (): Promise<void> => {
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();
};

0 comments on commit 567da28

Please sign in to comment.