Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript definitions #736

Merged
merged 95 commits into from
Dec 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
95 commits
Select commit Hold shift + click to select a range
f9cc7f9
First pass
rattrayalex-stripe Nov 22, 2019
79a54e7
wip
rattrayalex-stripe Nov 22, 2019
f8f6158
More changes
rattrayalex-stripe Nov 25, 2019
c6dd7be
Split resources by file
rattrayalex-stripe Nov 26, 2019
a1bc7bc
Move to api version folder
jlomas-stripe Nov 27, 2019
a6afc7e
Remove tsconfig, add prettierignore
rattrayalex-stripe Nov 27, 2019
e263d1b
Properly generate nested and no-method resources
rattrayalex-stripe Nov 27, 2019
3c83542
Document new TypeScript usage in README
rattrayalex-stripe Nov 27, 2019
2dcecfa
Add a basic test for typescript correctness
rattrayalex-stripe Nov 27, 2019
24fbd0a
Better formatting for export of Stripe
rattrayalex-stripe Nov 27, 2019
1df6c5f
Break out subtypes
rattrayalex-stripe Nov 27, 2019
5bcade6
Separate out Address
rattrayalex-stripe Nov 27, 2019
d23ae00
Pull empty strings out of enums
rattrayalex-stripe Nov 27, 2019
02b9ed0
Use all named subresources from openapi
rattrayalex-stripe Nov 27, 2019
5bc4d28
Rough draft of using shared subresources
rattrayalex-stripe Nov 27, 2019
1776bd0
Revert "Rough draft of using shared subresources"
rattrayalex-stripe Nov 27, 2019
78b4a69
Fix some bugs I think
rattrayalex-stripe Nov 27, 2019
4a9448f
Okay actually go back to normal
rattrayalex-stripe Nov 27, 2019
ed1f7ed
Actually use all shared subresources from openapi
rattrayalex-stripe Nov 27, 2019
b4da417
Revert "Actually use all shared subresources from openapi"
rattrayalex-stripe Nov 27, 2019
aefd234
Add and test ApiListPromise for async iteration of lists
rattrayalex-stripe Nov 30, 2019
32b92d1
Add better types for ApiList and HeaderOptions
rattrayalex-stripe Nov 30, 2019
402f267
Rename HeaderOptions to RequestOptions
rattrayalex-stripe Nov 30, 2019
f98115b
Add docs and tests for expanding objects
rattrayalex-stripe Nov 30, 2019
4b63ed5
Add webhooks.d.ts
jlomas-stripe Nov 29, 2019
f5d139f
Add in reference to webhooks.d.ts
jlomas-stripe Dec 2, 2019
b4abeb9
Update snapshots to reflect reordering
rattrayalex-stripe Dec 3, 2019
a59fbd9
Add multiple dispatch for optional params
rattrayalex-stripe Dec 3, 2019
8a99a8c
Add TS tests for multiple dispatch, config, etc
rattrayalex-stripe Dec 3, 2019
1cc318f
Move types for setAppInfo
rattrayalex-stripe Dec 4, 2019
876008a
Add errors
rattrayalex-stripe Dec 4, 2019
e5fdc27
Fix some formatting
rattrayalex-stripe Dec 4, 2019
45903c0
Remove (Customer) Source and ExternalAccount
rattrayalex-stripe Dec 4, 2019
aaa28e4
Move metadata back up, add deleted?: void, add eg DeletedCustomer to …
rattrayalex-stripe Dec 4, 2019
6a8ff81
Reorder nested methods, rename nested & delete param types, move nest…
rattrayalex-stripe Dec 4, 2019
45b33ed
Remove docstrings from param types since they exist on method definit…
rattrayalex-stripe Dec 4, 2019
4545ff2
Reorder required params to be first
rattrayalex-stripe Dec 4, 2019
b40e08e
Minor method reorder
rattrayalex-stripe Dec 5, 2019
2d8ebb2
Describe why you have to explicitly reference the types
rattrayalex-stripe Dec 5, 2019
440bacf
Move from vYYYY-MM-DD to YYYY-MM-DD, upgrade api version to 2019-12-03
rattrayalex-stripe Dec 5, 2019
39eaa02
Update future version
rattrayalex-stripe Dec 5, 2019
7fd97ad
Fix param type name and mention esModuleInterop in docs
rattrayalex-stripe Dec 6, 2019
183847b
Add docstring and test for ApiList
rattrayalex-stripe Dec 7, 2019
89527f6
Add docstrings for errors
rattrayalex-stripe Dec 7, 2019
3ecf986
Fix accidentally optional fields
rattrayalex-stripe Dec 7, 2019
d7d5f74
Add missing values to RawErrorType
rattrayalex-stripe Dec 7, 2019
f7fa356
Fix many non-optional fields
rattrayalex-stripe Dec 10, 2019
ad95619
Remove whitespace typo
rattrayalex-stripe Dec 10, 2019
e78e5b5
Add signature for retrieving a specific account
rattrayalex-stripe Dec 10, 2019
9c3657e
Add types for OAuth
rattrayalex-stripe Dec 10, 2019
de0717a
Openapi updates
rattrayalex-stripe Dec 10, 2019
4ff08ef
Rename Webhooks in git
rattrayalex-stripe Dec 11, 2019
10e7ec9
Use export default instead of export = so that users dont need to do …
rattrayalex-stripe Dec 13, 2019
8256746
Add a default export to the runtime
rattrayalex-stripe Dec 16, 2019
2c24d0f
Also export Stripe as a named export, and as a static property on itself
rattrayalex-stripe Dec 17, 2019
d341ad3
Collapse types for setHost
rattrayalex-stripe Dec 17, 2019
e94b945
Require the user to specify the latest API version, use types by defa…
rattrayalex-stripe Dec 17, 2019
28fb782
Fix a type error
rattrayalex-stripe Dec 17, 2019
d3a054f
Reorganize test, use strictNullChecks etc
rattrayalex-stripe Dec 17, 2019
5ea1576
Fix readme
rattrayalex-stripe Dec 17, 2019
5134a6e
Unexport error classes to avoid instanceof confusion
rattrayalex-stripe Dec 17, 2019
d2fa486
Clarify how to use old api versions with TS
rattrayalex-stripe Dec 17, 2019
a9389ab
Fix typo params -> param
rattrayalex-stripe Dec 19, 2019
3fa47a7
Updates from openapi
rattrayalex-stripe Dec 19, 2019
cd08ae3
Mark the args to several setters as required
rattrayalex-stripe Dec 19, 2019
06fe260
More accurate handling of deleted resources and required/optional fields
rattrayalex-stripe Dec 20, 2019
142345c
Erroneous handling of deleted
rattrayalex-stripe Dec 20, 2019
09503eb
Revert "Erroneous handling of deleted"
rattrayalex-stripe Dec 20, 2019
2dfaa3a
Add comment about deprecated total_count.
rattrayalex-stripe Dec 20, 2019
a919f34
Add shared types for Addresses and Metadata, and update openapi
rattrayalex-stripe Dec 21, 2019
ff16fd2
Use null intead of empty string
rattrayalex-stripe Dec 21, 2019
67d8000
Fix invoice upcoming lines
rattrayalex-stripe Dec 21, 2019
eaf4bcf
Update openapi
rattrayalex-stripe Dec 21, 2019
17e0b16
More empty-string to null translation
rattrayalex-stripe Dec 23, 2019
4a40faf
Stop polluting the global namespace by scoping everything under modul…
rattrayalex-stripe Dec 23, 2019
a92130d
Run eslint & prettier on TS files
rattrayalex-stripe Dec 23, 2019
b95fb5a
Continue to have poor types for HttpAgent, but with more claity as to…
rattrayalex-stripe Dec 23, 2019
9da055c
Clean up explicit any lint warnings
rattrayalex-stripe Dec 23, 2019
afc68c0
Remove constants intended for internal use only
rattrayalex-stripe Dec 23, 2019
0bb34d9
Extract CustomerSource to a standalone type
rattrayalex-stripe Dec 23, 2019
fcdff4f
Remove unnecessary export
rattrayalex-stripe Dec 23, 2019
47dcdf7
Better types for account debit sources
rattrayalex-stripe Dec 23, 2019
258105c
Use shared RangeQueryParam and PaginationParam
rattrayalex-stripe Dec 24, 2019
5147b69
Add expand param to SubscriptionDeleteParams
rattrayalex-stripe Dec 24, 2019
2d144c2
Bring business_type back
rattrayalex-stripe Dec 24, 2019
8113f5d
Add docstrings to config options
rattrayalex-stripe Dec 24, 2019
b62f291
Add mandatory `typescript: true` config prop
rattrayalex-stripe Dec 24, 2019
718ebd0
Use await in TS readme
rattrayalex-stripe Dec 24, 2019
e9195cd
Wrap await in async function
rattrayalex-stripe Dec 24, 2019
2dfb996
Many readme updates
rattrayalex-stripe Dec 24, 2019
5642eb2
Remove docs on non-public fields/params (we should revert this if it …
rattrayalex-stripe Dec 24, 2019
578a768
Clarify async/await a bit
rattrayalex-stripe Dec 24, 2019
5dd9b15
TypeScriptify docstrings for Webhooks
rattrayalex-stripe Dec 24, 2019
c3de77e
Add @types/node as a dependency, use it for typing Buffer and http.Agent
rattrayalex-stripe Dec 24, 2019
4ddd611
Remove a TODO
rattrayalex-stripe Dec 24, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 105 additions & 99 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,20 @@
The Stripe Node library provides convenient access to the Stripe API from
applications written in server-side JavaScript.

Please keep in mind that this package is for use with server-side Node that
uses Stripe secret keys. To maintain PCI compliance, tokenization of credit
card information should always be done with [Stripe.js][stripe-js] on the
client side. This package should not be used for that purpose.
For collecting customer and payment information in the browser, use [Stripe.js][stripe-js].

## Documentation

See the [`stripe-node` API docs](https://stripe.com/docs/api/node#intro) for Node.js.
See the [`stripe-node` API docs](https://stripe.com/docs/api?lang=node) for Node.js.

## Installation

Install the package with:

```sh
npm install stripe --save
# or
yarn add stripe
```

## Usage
Expand All @@ -32,73 +31,83 @@ The package needs to be configured with your account's secret key which is
available in your [Stripe Dashboard][api-keys]. Require it with the key's
value:

<!-- prettier-ignore -->
```js
const stripe = require('stripe')('sk_test_...');

const customer = await stripe.customers.create({
stripe.customers.create({
email: '[email protected]',
});
})
.then(customer => console.log(customer.id))
.catch(error => console.error(error));
```

Or using ES modules, this looks more like:
Or using ES modules and `async`/`await`:

```js
import Stripe from 'stripe';
const stripe = Stripe('sk_test_...');
//…
const stripe = new Stripe('sk_test_...');

(async () => {
const customer = await stripe.customers.create({
email: '[email protected]',
});

console.log(customer.id);
})();
```

## Initialize with config object
### Usage with TypeScript

The package can be initialized with several options:
As of 8.0.0, Stripe maintains types for the latest [API version][api-versions].

```js
import ProxyAgent from 'https-proxy-agent';
Import Stripe as a default import (not `* as Stripe`, unlike the DefinitelyTyped version)
and instantiate it as `new Stripe()` with the latest API version.

const stripe = Stripe('sk_test_...', {
apiVersion: '2019-08-08',
maxNetworkRetries: 1,
httpAgent: new ProxyAgent(process.env.http_proxy),
timeout: 1000,
host: 'api.example.com',
port: 123,
telemetry: true,
```ts
import Stripe from 'stripe';
const stripe = new Stripe('sk_test_...', {
apiVersion: '2019-12-03',
Copy link
Contributor

@richardm-stripe richardm-stripe Dec 24, 2019

Choose a reason for hiding this comment

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

Let's make sure our release script updates this automatically.

typescript: true,
});
```

| Option | Default | Description |
| ------------------- | ----------------------------- | ------------------------------------------------------------------------------------- |
| `apiVersion` | `null` | Stripe API version to be used. If not set the account's default version will be used. |
| `maxNetworkRetries` | 0 | The amount of times a request should be [retried](#network-retries). |
| `httpAgent` | `null` | [Proxy](#configuring-a-proxy) agent to be used by the library. |
| `timeout` | 120000 (Node default timeout) | [Maximum time each request can take in ms.](#configuring-timeout) |
| `host` | `'api.stripe.com'` | Host that requests are made to. |
| `port` | 443 | Port that requests are made to. |
| `telemetry` | `true` | Allow Stripe to send latency [telemetry](#request-latency-telemetry) |
const createCustomer = async () => {
const params: Stripe.CustomerCreateParams = {
description: 'test customer',
};

Note: Both `maxNetworkRetries` and `timeout` can be overridden on a per-request basis. `timeout` can be updated at any time with [`stripe.setTimeout`](#configuring-timeout).
const customer: Stripe.Customer = await stripe.customers.create(params);

### Usage with TypeScript
console.log(customer.id);
};
createCustomer();
```

Stripe does not currently maintain typings for this package, but there are
community typings available from DefinitelyTyped.
#### Using old API versions with TypeScript

To install:
Types can change between API versions (eg; Stripe may have changed a field from a string to a hash),
Copy link
Contributor

Choose a reason for hiding this comment

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

e.g., I think is our style

so our types only reflect the latest API version.

```sh
npm install --dev @types/stripe
```
We therefore encourage [upgrading your API version][api-version-upgrading]
if you would like to take advantage of Stripe's TypeScript definitions.

To use:
If you are on an older API version (eg; `2019-10-17`) and not able to upgrade,
you may pass another version or `apiVersion: null` to use your account's default API version,
and use a comment like `// @ts-ignore stripe-version-2019-10-17` to silence type errors here
and anywhere the types differ between your API version and the latest.
When you upgrade, you should remove these comments.

```ts
// Note `* as` and `new Stripe` for TypeScript:
import * as Stripe from 'stripe';
const stripe = new Stripe('sk_test_...');
#### Using `expand` with TypeScript

const customer: Promise<
Stripe.customers.ICustomer
> = stripe.customers.create(/* ... */);
[Expandable][expanding_objects] fields are typed as `string | Foo`,
so you must cast them appropriately, eg;

```ts
const charge: Stripe.Charge = await stripe.charges.retrieve('ch_123', {
expand: ['customer'],
});
const customerEmail: string = (charge.customer as Stripe.Customer).email;
const btId: string = charge.balance_transaction as string;
```

### Using Promises
Expand Down Expand Up @@ -132,62 +141,81 @@ stripe.customers
});
```

### Configuring Timeout
## Configuration

### Initialize with config object

Request timeout is configurable (the default is Node's default of 120 seconds):
The package can be initialized with several options:

```js
stripe.setTimeout(20000); // in ms (this is 20 seconds)
import ProxyAgent from 'https-proxy-agent';

const stripe = Stripe('sk_test_...', {
apiVersion: '2019-08-08',
maxNetworkRetries: 1,
httpAgent: new ProxyAgent(process.env.http_proxy),
timeout: 1000,
host: 'api.example.com',
port: 123,
telemetry: true,
});
```

Timeout can also be set globally via the config object:
| Option | Default | Description |
| ------------------- | ----------------------------- | ------------------------------------------------------------------------------------- |
| `apiVersion` | `null` | Stripe API version to be used. If not set the account's default version will be used. |
| `maxNetworkRetries` | 0 | The amount of times a request should be [retried](#network-retries). |
| `httpAgent` | `null` | [Proxy](#configuring-a-proxy) agent to be used by the library. |
| `timeout` | 120000 (Node default timeout) | [Maximum time each request can take in ms.](#configuring-timeout) |
| `host` | `'api.stripe.com'` | Host that requests are made to. |
| `port` | 443 | Port that requests are made to. |
| `telemetry` | `true` | Allow Stripe to send latency [telemetry](#request-latency-telemetry) |

Note: Both `maxNetworkRetries` and `timeout` can be overridden on a per-request basis.

### Configuring Timeout

Timeout can be set globally via the config object:

```js
const stripe = Stripe('sk_test_...', {
timeout: 2000,
timeout: 20 * 1000, // 20 seconds
});
```

And on a per-request basis:
And overridden on a per-request basis:

```js
stripe.customers.create(
{
email: '[email protected]',
},
{
timeout: 1000,
timeout: 1000, // 1 second
}
);
```

If `timeout` is set globally via the config object, the value set in a per-request basis will be favored.

### Configuring For Connect

A per-request `Stripe-Account` header for use with [Stripe Connect][connect]
can be added to any method:

```js
// Retrieve the balance for a connected account:
stripe.balance
.retrieve({
// List the balance transactions for a connected account:
stripe.balanceTransactions.list(
{
limit: 10,
},
{
stripeAccount: 'acct_foo',
})
.then((balance) => {
// The balance object for the connected account
})
.catch((err) => {
// Error
});
}
);
```

### Configuring a Proxy

An [https-proxy-agent][https-proxy-agent] can be configured with
`setHttpAgent`.

To use stripe behind a proxy you can pass to sdk on initialization:
To use stripe behind a proxy you can pass an [https-proxy-agent][https-proxy-agent] on initialization:

```js
if (process.env.http_proxy) {
Expand Down Expand Up @@ -338,7 +366,6 @@ This information is passed along when the library makes calls to the Stripe API.

### Auto-pagination

As of stripe-node 6.11.0, you may auto-paginate list methods.
We provide a few different APIs for this to aid with a variety of node versions and styles.

#### Async iterators (`for-await-of`)
Expand Down Expand Up @@ -389,32 +416,6 @@ stripe.customers
.catch(handleError);
```

If you prefer callbacks to promises, you may also use a `next` callback and a second `onDone` callback:

```js
stripe.customers.list().autoPagingEach(
function onItem(customer, next) {
doSomething(customer, function(err, result) {
if (shouldStop(result)) {
next(false); // Passing `false` breaks out of the loop.
} else {
next();
}
});
},
function onDone(err) {
if (err) {
console.error(err);
} else {
console.log('Done iterating.');
}
}
);
```

If your `onItem` function does not accept a `next` callback parameter _or_ return a Promise,
the return value is used to decide whether to continue (`false` breaks, anything else continues).

#### `autoPagingToArray`

This is a convenience for cases where you expect the number of items
Expand All @@ -437,7 +438,9 @@ numbers help Stripe improve the overall latency of its API for all users.
You can disable this behavior if you prefer:

```js
stripe.setTelemetryEnabled(false);
const stripe = new Stripe('sk_test_...', {
telemetry: false,
});
```

## More Information
Expand Down Expand Up @@ -487,7 +490,10 @@ $ yarn fix
```

[api-keys]: https://dashboard.stripe.com/account/apikeys
[api-versions]: https://stripe.com/docs/api/versioning
[api-version-upgrading]: https://stripe.com/docs/upgrades#how-can-i-upgrade-my-api
[connect]: https://stripe.com/connect
[expanding_objects]: https://stripe.com/docs/api/expanding_objects
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[stripe-js]: https://stripe.com/docs/stripe.js

Expand Down
29 changes: 14 additions & 15 deletions lib/resources/Accounts.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,25 @@ const stripeMethod = StripeResource.method;
module.exports = StripeResource.extend({
path: '',

reject: stripeMethod({
method: 'POST',
path: 'accounts/{account}/reject',
}),

create: stripeMethod({
method: 'POST',
path: 'accounts',
}),

del: stripeMethod({
method: 'DELETE',
path: 'accounts/{account}',
}),

list: stripeMethod({
method: 'GET',
path: 'accounts',
methodType: 'list',
}),

update: stripeMethod({
reject: stripeMethod({
method: 'POST',
path: 'accounts/{id}',
}),

// Avoid 'delete' keyword in JS
del: stripeMethod({
method: 'DELETE',
path: 'accounts/{id}',
path: 'accounts/{account}/reject',
}),

retrieve(id) {
Expand All @@ -54,9 +48,9 @@ module.exports = StripeResource.extend({
}
},

createLoginLink: stripeMethod({
update: stripeMethod({
method: 'POST',
path: 'accounts/{account}/login_links',
path: 'accounts/{account}',
}),

listCapabilities: stripeMethod({
Expand Down Expand Up @@ -101,6 +95,11 @@ module.exports = StripeResource.extend({
path: 'accounts/{account}/external_accounts/{id}',
}),

createLoginLink: stripeMethod({
method: 'POST',
path: 'accounts/{account}/login_links',
}),

createPerson: stripeMethod({
method: 'POST',
path: 'accounts/{account}/persons',
Expand Down
1 change: 1 addition & 0 deletions lib/resources/Balance.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ module.exports = StripeResource.extend({

retrieve: stripeMethod({
method: 'GET',
path: '',
}),
});
Loading