forked from stripe/sync-engine
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathclient.ts
More file actions
179 lines (156 loc) · 5.53 KB
/
client.ts
File metadata and controls
179 lines (156 loc) · 5.53 KB
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
import {
StripeAccountSchema,
StripeWebhookEndpointSchema,
StripeApiListSchema,
StripeApiRequestError,
pickDebugHeaders,
type StripeAccount,
type StripeApiList,
type StripeWebhookEndpoint,
} from '@stripe/sync-openapi'
import { withHttpRetry } from './retry.js'
import { stripeEventSchema, type StripeEvent } from './spec.js'
import { tracedFetch, parsePositiveInteger, type TransportEnv } from './transport.js'
export type StripeClientConfig = {
api_key: string
api_version: string
base_url?: string
}
export { getProxyUrl as getStripeProxyUrl } from './transport.js'
const DEFAULT_STRIPE_API_BASE = 'https://api.stripe.com'
export { StripeApiRequestError as StripeRequestError }
export type StripeClient = ReturnType<typeof makeClient>
export function makeClient(
config: StripeClientConfig,
env: TransportEnv = process.env,
pipelineSignal?: AbortSignal
) {
const baseUrl = (config.base_url ?? DEFAULT_STRIPE_API_BASE).replace(/\/$/, '')
const timeoutMs = parsePositiveInteger(
'STRIPE_REQUEST_TIMEOUT_MS',
env.STRIPE_REQUEST_TIMEOUT_MS,
10_000
)
const headers: Record<string, string> = {
Authorization: `Bearer ${config.api_key}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Stripe-Version': config.api_version,
}
async function request(
method: string,
path: string,
params?: Record<string, unknown>
): Promise<unknown> {
const url = new URL(path, baseUrl)
let body: string | undefined
if (method === 'GET' && params) {
appendSearchParams(url.searchParams, params)
} else if (params) {
body = encodeFormData(params)
}
const signals: AbortSignal[] = [AbortSignal.timeout(timeoutMs)]
if (pipelineSignal) signals.push(pipelineSignal)
const signal = signals.length === 1 ? signals[0]! : AbortSignal.any(signals)
const response = await tracedFetch(url.toString(), { method, headers, body, signal })
const debugHeaders = pickDebugHeaders(response.headers)
const text = await response.text()
let json: unknown
try {
json = JSON.parse(text)
} catch {
const preview = text.slice(0, 200).replace(/[\r\n]+/g, '\\n')
throw new StripeApiRequestError(
response.status,
{ error: { message: `Non-JSON response: ${preview}` } },
method,
path,
debugHeaders
)
}
if (!response.ok) {
throw new StripeApiRequestError(response.status, json, method, path, debugHeaders)
}
return json
}
/**
* Wraps `request` with retry logic for GET requests only.
* Non-GET methods (POST, DELETE) pass through without retry to avoid
* duplicating side effects.
*/
async function requestWithRetry(
method: string,
path: string,
params?: Record<string, unknown>,
opts?: { maxRetries?: number }
): Promise<unknown> {
if (method === 'GET') {
return withHttpRetry(() => request(method, path, params), {
label: `${method} ${path}`,
signal: pipelineSignal,
maxRetries: opts?.maxRetries,
})
}
return request(method, path, params)
}
return {
async getAccount(opts?: { maxRetries?: number }): Promise<StripeAccount> {
const json = await requestWithRetry('GET', '/v1/account', undefined, opts)
return StripeAccountSchema.parse(json)
},
async listEvents(params: {
created?: { gt: number }
limit?: number
starting_after?: string
}): Promise<StripeApiList<StripeEvent>> {
const query: Record<string, unknown> = {}
if (params.limit) query.limit = params.limit
if (params.starting_after) query.starting_after = params.starting_after
if (params.created?.gt) query['created[gt]'] = params.created.gt
const json = await requestWithRetry('GET', '/v1/events', query)
return StripeApiListSchema(stripeEventSchema).parse(json)
},
async listWebhookEndpoints(params?: {
limit?: number
}): Promise<StripeApiList<StripeWebhookEndpoint>> {
const json = await requestWithRetry('GET', '/v1/webhook_endpoints', params)
return StripeApiListSchema(StripeWebhookEndpointSchema).parse(json)
},
async createWebhookEndpoint(params: {
url: string
enabled_events: string[]
api_version: string
metadata?: Record<string, string>
}): Promise<StripeWebhookEndpoint> {
const json = await requestWithRetry('POST', '/v1/webhook_endpoints', params)
return StripeWebhookEndpointSchema.parse(json)
},
async deleteWebhookEndpoint(id: string): Promise<void> {
await requestWithRetry('DELETE', `/v1/webhook_endpoints/${encodeURIComponent(id)}`)
},
}
}
// MARK: - URL encoding helpers
function appendSearchParams(sp: URLSearchParams, params: Record<string, unknown>) {
for (const [key, value] of Object.entries(params)) {
if (value != null) {
sp.set(key, String(value))
}
}
}
function encodeFormData(params: Record<string, unknown>, prefix = ''): string {
const parts: string[] = []
for (const [key, value] of Object.entries(params)) {
const fullKey = prefix ? `${prefix}[${key}]` : key
if (value == null) continue
if (typeof value === 'object' && !Array.isArray(value)) {
parts.push(encodeFormData(value as Record<string, unknown>, fullKey))
} else if (Array.isArray(value)) {
for (const item of value) {
parts.push(`${encodeURIComponent(`${fullKey}[]`)}=${encodeURIComponent(String(item))}`)
}
} else {
parts.push(`${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`)
}
}
return parts.filter(Boolean).join('&')
}