-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathseam-http-request.ts
More file actions
219 lines (188 loc) · 5.98 KB
/
Copy pathseam-http-request.ts
File metadata and controls
219 lines (188 loc) · 5.98 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
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
import type { Method } from 'axios'
import type { Client } from './client.js'
import type { SeamHttpRequestOptions } from './options.js'
import { assertValidRequestParameters } from './request-parameters.js'
import {
type ActionAttemptsClient,
resolveActionAttempt,
} from './resolve-action-attempt.js'
import type { ActionAttempt } from './resources/action-attempt.js'
import { serializeUrlSearchParams } from './url-search-params-serializer.js'
interface SeamHttpRequestParent {
readonly client: Client
readonly defaults: Required<SeamHttpRequestOptions>
}
interface SeamHttpRequestConfig<TResponseKey> {
readonly pathname: string
readonly method: Method
readonly body?: unknown
readonly params?: undefined | Record<string, unknown>
readonly responseKey: TResponseKey
readonly hasPagination?: boolean
readonly options?: Pick<SeamHttpRequestOptions, 'waitForActionAttempt'>
readonly actionAttempts?: ActionAttemptsClient
readonly parameters?: unknown
readonly hasRequiredParameters?: boolean
readonly requiredParameterNames?: readonly string[]
}
export class SeamHttpRequest<
const TResponse,
const TResponseKey extends keyof TResponse | undefined,
> implements Promise<
TResponseKey extends keyof TResponse ? TResponse[TResponseKey] : undefined
> {
readonly [Symbol.toStringTag]: string = 'SeamHttpRequest'
readonly #parent: SeamHttpRequestParent
readonly #config: SeamHttpRequestConfig<TResponseKey>
constructor(
parent: SeamHttpRequestParent,
config: SeamHttpRequestConfig<TResponseKey>,
) {
this.#parent = parent
this.#config = config
}
public get responseKey(): TResponseKey {
return this.#config.responseKey
}
public get hasPagination(): boolean {
return this.#config.hasPagination ?? false
}
public get url(): URL {
const { client } = this.#parent
const serializer =
typeof client.defaults.paramsSerializer === 'function'
? client.defaults.paramsSerializer
: serializeUrlSearchParams
const origin = getUrlPrefix(client.defaults.baseURL ?? '')
const path =
this.params == null
? this.pathname
: `${this.pathname}?${serializer(this.params)}`
return new URL(`${origin}${path}`)
}
public get pathname(): string {
return this.#config.pathname.startsWith('/')
? this.#config.pathname
: `/${this.#config.pathname}`
}
public get method(): Method {
return this.#config.method
}
public get params(): undefined | Record<string, unknown> {
return this.#config.params
}
public get body(): unknown {
return this.#config.body
}
async execute(): Promise<
TResponseKey extends keyof TResponse ? TResponse[TResponseKey] : undefined
> {
const response = await this.fetchResponse()
type Response = TResponseKey extends keyof TResponse
? TResponse[TResponseKey]
: undefined
if (this.responseKey === undefined) {
return undefined as Response
}
const data = response[this.responseKey] as unknown as Response
if (this.responseKey === 'action_attempt') {
const waitForActionAttempt =
this.#config.options?.waitForActionAttempt ??
this.#parent.defaults.waitForActionAttempt
if (waitForActionAttempt !== false) {
if (this.#config.actionAttempts == null) {
throw new Error(
'Cannot wait for an action attempt without an action attempts client',
)
}
const actionAttempt = await resolveActionAttempt(
data as unknown as ActionAttempt,
this.#config.actionAttempts,
typeof waitForActionAttempt === 'boolean' ? {} : waitForActionAttempt,
)
return actionAttempt as Response
}
}
return data
}
async fetchResponse(): Promise<TResponse> {
assertValidRequestParameters(
this.#config.parameters,
this.pathname,
this.#config.hasRequiredParameters ?? false,
this.#config.requiredParameterNames ?? [],
)
const { client } = this.#parent
const response = await client.request({
url: this.pathname,
method: this.method,
data: this.body,
params: this.params,
})
return response.data as unknown as TResponse
}
async then<
TResult1 = TResponseKey extends keyof TResponse
? TResponse[TResponseKey]
: undefined,
TResult2 = never,
>(
onfulfilled?:
| ((
value: TResponseKey extends keyof TResponse
? TResponse[TResponseKey]
: undefined,
) => TResult1 | PromiseLike<TResult1>)
| null
| undefined,
onrejected?:
| ((reason: unknown) => TResult2 | PromiseLike<TResult2>)
| null
| undefined,
): Promise<TResult1 | TResult2> {
return await this.execute().then(onfulfilled, onrejected)
}
async catch<TResult = never>(
onrejected?:
((reason: unknown) => TResult | PromiseLike<TResult>) | null | undefined,
): Promise<
| (TResponseKey extends keyof TResponse
? TResponse[TResponseKey]
: undefined)
| TResult
> {
return await this.execute().catch(onrejected)
}
async finally(
onfinally?: (() => void) | null | undefined,
): Promise<
TResponseKey extends keyof TResponse ? TResponse[TResponseKey] : undefined
> {
return await this.execute().finally(onfinally)
}
}
const getUrlPrefix = (input: string): string => {
if (canParseUrl(input)) {
const url = new URL(input).toString()
if (url.endsWith('/')) return url.slice(0, -1)
return url
}
if (globalThis.location != null) {
const pathname = input.startsWith('/') ? input : `/${input}`
return new URL(`${globalThis.location.origin}${pathname}`)
.toString()
.replace(/\/$/, '')
}
throw new Error(
`Cannot resolve origin from ${input} in a non-browser environment`,
)
}
// UPSTREAM: Prefer URL.canParse when it has wider support.
// https://caniuse.com/mdn-api_url_canparse_static
const canParseUrl = (input: string): boolean => {
try {
return new URL(input) != null
} catch {
return false
}
}