-
Notifications
You must be signed in to change notification settings - Fork 724
/
typescriptTest.ts
296 lines (253 loc) · 8.39 KB
/
typescriptTest.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/**
* This file does not exist to be executed, just compiled,
* so that we can ensure that the definition files
* only reference names that exist,
* and to perform a basic sanity check that types are exported as intended.
*/
///<reference types="../2020-08-27" />
import Stripe from 'stripe';
let stripe = new Stripe('sk_test_123', {
apiVersion: '2020-08-27',
});
// @ts-ignore lazily ignore apiVersion requirement.
stripe = new Stripe('sk_test_123');
stripe = new Stripe('sk_test_123', {
// @ts-ignore ignore specific apiVersion.
apiVersion: '2019-11-05',
});
stripe = new Stripe('sk_test_123', {
// @ts-ignore ignore default apiVersion.
apiVersion: null,
});
// Check config object.
stripe = new Stripe('sk_test_123', {
apiVersion: '2020-08-27',
typescript: true,
maxNetworkRetries: 1,
timeout: 1000,
host: 'api.example.com',
port: 123,
telemetry: true,
httpClient: Stripe.createNodeHttpClient(),
});
stripe.setTimeout(3000);
stripe.setAppInfo({
name: 'my-wordpress-plugin',
});
stripe.setHost('host', 'port', 'protocol');
(async (): Promise<void> => {
const params: Stripe.CustomerCreateParams = {
description: 'test',
};
const opts: Stripe.RequestOptions = {
apiVersion: '2020-08-27',
};
const customer: Stripe.Customer = await stripe.customers.create(params, opts);
const address: Stripe.Address | null = customer.address;
if (!address) return;
const city: string | null = address.city;
// Check no opts:
await stripe.customers.create(params);
// Check multiple dispatch:
let product = await stripe.products.retrieve('prod_123', opts);
product = await stripe.products.retrieve('prod_123', {expand: []}, opts);
const charge: Stripe.Charge = await stripe.charges.retrieve('ch_123', {
expand: ['customer'],
});
// Ignore null case.
if (!charge.customer) throw Error('guard');
// Check you can cast an expandable field to the object:
const cusEmail: string | null = (charge.customer as Stripe.Customer).email;
// Check you can cast an expandable field to a string:
const btId: string = charge.balance_transaction as string;
// Check you can deal with deleted:
if (
typeof charge.customer !== 'string' &&
// Not sure why `!charge.customer.deleted` doesn't work, it seems to in a playground:
// https://www.typescriptlang.org/play/index.html#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChnJwBcyAzmFKAOYDc+yADpQgNYA2AnieZSLfXABGiFtwrVkAH2QgArmzZSZsgLaDodAmA4MIJAOQxM+zcgAmENhEhmA-CQBu6YGboBfXKEixEKACKW1hBmGFh4Wjp6yIbGphZWNiQUshDuuLjausgAsnAc6qHIALxomEoBCcGh6RYIbHBQKAjoIOTIAB4kufkQ1Z4wyAAUAITtAHTxQWYAlDj0za1ghGK8VMUdY3C4Hri19Y3IC21cpVjSFVOF0jwS0nIK6cADgxzIAGRvyJkQ6AOvw0USvobnx9O9PsMOBNAjZZuFDi02sQyOI+OsoVsPEA
// Might be a complexity limit with our resources: https://github.com/microsoft/TypeScript/pull/30779/files#diff-c3ed224e4daa84352f7f1abcd23e8ccaR13219
!('deleted' in charge.customer)
) {
const created: number = charge.customer.created;
}
const r = Math.random() - 0.5;
// Okay, this is how I hope people can deal with deleted:
const maybeCoupon: Stripe.Coupon | Stripe.DeletedCoupon = await (r
? stripe.coupons.retrieve('25_off')
: stripe.coupons.del('25_off'));
if (maybeCoupon.deleted) {
const d: true = maybeCoupon.deleted;
} else {
// Here, TS knows it's a full Coupon.
const created: number = maybeCoupon.created;
}
for await (const customer of stripe.customers.list()) {
const {id} = customer as Stripe.Customer;
if (id === 'hi') {
break;
}
}
const cusList: Stripe.ApiList<Stripe.Customer> = await stripe.customers.list();
const aThousandCustomers: Array<Stripe.Customer> = await stripe.customers
.list()
.autoPagingToArray({limit: 1000});
const nothing: void = await stripe.customers
.list()
.autoPagingEach((customer: Stripe.Customer) => {
if (customer.id === 'one') {
return false;
}
if (customer.id === 'two') {
return Promise.resolve(false);
}
if (customer.id === 'three') {
return Promise.resolve();
}
return undefined;
});
try {
await stripe.paymentIntents.create({amount: 100, currency: 'USD'});
} catch (err) {
if (err instanceof stripe.errors.StripeCardError) {
const declineCode: string = err.decline_code;
}
if (err instanceof Stripe.errors.StripeCardError) {
const declineCode: string = err.decline_code;
}
}
{
const custs = await stripe.customers.list();
const lr = custs.lastResponse;
const requestId: string = lr.requestId;
const statusCode: number = lr.statusCode;
const apiVersion: string | undefined = lr.apiVersion;
const idempotencyKey: string | undefined = lr.idempotencyKey;
const headers = lr.headers;
const header: string | undefined = headers['request-id'];
}
{
const cust = await stripe.customers.retrieve('foo');
const lr = cust.lastResponse;
const requestId: string = lr.requestId;
const statusCode: number = lr.statusCode;
const apiVersion: string | undefined = lr.apiVersion;
const idempotencyKey: string | undefined = lr.idempotencyKey;
const headers = lr.headers;
const header: string | undefined = lr.headers['request-id'];
}
{
const acct = await stripe.accounts.createExternalAccount('foo', {
['external_account']: 'foo',
});
if (acct.object === 'card') {
const rid: string = acct.lastResponse.requestId;
}
}
})();
const stripeCardError: Stripe.StripeCardError = Stripe.errors.generate({
type: 'card_error',
code: 'card_declined',
charge: 'ch_123',
});
const Foo = Stripe.StripeResource.extend({
includeBasic: ['retrieve'],
foo: Stripe.StripeResource.method({
method: 'create',
path: 'foo',
}),
fooFullPath: Stripe.StripeResource.method({
method: 'create',
fullPath: '/v1/full/path',
}),
search: Stripe.StripeResource.method({
method: 'create',
fullPath: 'foo',
methodType: 'search',
}),
customer: Stripe.StripeResource.method<Stripe.Customer>({method: 'POST'}),
});
const fooClient = new Foo(stripe);
const searchResponse: Stripe.Response<object> = fooClient.search();
const customerResponse: Stripe.Response<Stripe.Customer> = fooClient.customer();
const maxBufferedRequestMetrics: number =
Stripe.StripeResource.MAX_BUFFERED_REQUEST_METRICS;
// Test NodeHttpClient request processing.
import {Agent} from 'http';
async (): Promise<void> => {
const client = Stripe.createNodeHttpClient(new Agent());
const response = await client.makeRequest(
'api.stripe.com',
'443',
'/test',
'POST',
{
'Stripe-Account': 'account',
'Content-Length': 123,
},
'requestdata',
'https',
80000
);
const stream: Stripe.StripeStreamResponse = response.toStream(() => {
return;
});
stream.setEncoding('utf8');
const jsonResponse: object = await response.toJSON();
};
// Test FetchHttpClient request processing.
async (): Promise<void> => {
const client = Stripe.createFetchHttpClient();
const response = await client.makeRequest(
'api.stripe.com',
'443',
'/test',
'POST',
{
'Stripe-Account': 'account',
'Content-Length': 123,
},
'requestdata',
'https',
80000
);
const stream = response.toStream(() => {
return;
});
const results = await stream.getReader().read();
const jsonResponse: object = await response.toJSON();
};
// Tests asynchronous webhook processing.
async (): Promise<void> => {
const cryptoProvider = Stripe.createSubtleCryptoProvider();
const event = await stripe.webhooks.constructEventAsync(
'body',
'signature',
'secret',
undefined,
cryptoProvider
);
const event2 = await stripe.events.retrieve(event.id);
};
// Can reference error types
let errors: Stripe.Errors;
let rawError: Stripe.StripeRawError;
let oldError: Stripe.StripeError;
let newError: Stripe.errors.StripeError;
const instanceofCheck1 = {} instanceof Stripe.errors.StripeError;
const instanceofCheck2 = {} instanceof Stripe.errors.StripeAPIError;
const instanceofCheck3 = {} instanceof Stripe.StripeError;
const instanceofCheck4 = {} instanceof Stripe.StripeAPIError;
const instanceofCheck5 = {} instanceof stripe.errors.StripeError;
const instanceofCheck6 = {} instanceof stripe.errors.StripeAPIError;
Stripe.errors.generate({
type: 'card_error',
});
stripe.errors.generate({
type: 'card_error',
});
Stripe.StripeError.generate({
type: 'card_error',
});
Stripe.errors.StripeError.generate({
type: 'card_error',
});