-
-
Notifications
You must be signed in to change notification settings - Fork 393
/
HttpService.ts
270 lines (222 loc) · 8.39 KB
/
HttpService.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
import { LoggerInterface, joinPaths, sleep } from '@standardnotes/utils'
import { Environment } from '@standardnotes/models'
import { LegacySession, Result, Session, SessionToken } from '@standardnotes/domain-core'
import {
HttpStatusCode,
HttpRequestParams,
HttpVerb,
HttpRequest,
HttpResponse,
HttpResponseMeta,
isErrorResponse,
ApiEndpointParam,
} from '@standardnotes/responses'
import { HttpServiceInterface } from './HttpServiceInterface'
import { ApiVersion } from '../Api'
import { Paths } from '../Server/Auth/Paths'
import { SessionRefreshResponseBody } from '../Response/Auth/SessionRefreshResponseBody'
import { FetchRequestHandler } from './FetchRequestHandler'
import { RequestHandlerInterface } from './RequestHandlerInterface'
import { HttpRequestOptions } from './HttpRequestOptions'
export class HttpService implements HttpServiceInterface {
private session?: Session | LegacySession
private __latencySimulatorMs?: number
private __simulateNextSessionRefreshResponseDrop = false
private declare host: string
loggingEnabled = false
private inProgressRefreshSessionPromise?: Promise<Result<HttpResponse<SessionRefreshResponseBody>>>
private updateMetaCallback!: (meta: HttpResponseMeta) => void
private refreshSessionCallback!: (session: Session) => void
private requestHandler: RequestHandlerInterface
constructor(
private environment: Environment,
private appVersion: string,
private snjsVersion: string,
private apiVersion: ApiVersion,
private logger: LoggerInterface,
) {
this.requestHandler = new FetchRequestHandler(this.snjsVersion, this.appVersion, this.environment, this.logger)
}
setCallbacks(
updateMetaCallback: (meta: HttpResponseMeta) => void,
refreshSessionCallback: (session: Session) => void,
): void {
this.updateMetaCallback = updateMetaCallback
this.refreshSessionCallback = refreshSessionCallback
}
public deinit(): void {
;(this.session as unknown) = undefined
;(this.updateMetaCallback as unknown) = undefined
;(this.refreshSessionCallback as unknown) = undefined
}
setSession(session: Session | LegacySession): void {
this.session = session
}
setHost(host: string): void {
this.host = host
}
getHost(): string {
return this.host
}
private getSessionAccessToken(): string | undefined {
if (!this.session) {
return undefined
}
if (this.session instanceof Session) {
return this.session.accessToken.value
} else {
return this.session.accessToken
}
}
async get<T>(path: string, params?: HttpRequestParams, options?: HttpRequestOptions): Promise<HttpResponse<T>> {
if (!this.host) {
throw new Error('Attempting to make network request before host is set')
}
return this.runHttp({
url: joinPaths(this.host, path),
params,
verb: HttpVerb.Get,
authentication: options?.authentication ?? this.getSessionAccessToken(),
})
}
async getExternal<T>(url: string, params?: HttpRequestParams): Promise<HttpResponse<T>> {
return this.runHttp({
url,
params,
verb: HttpVerb.Get,
external: true,
})
}
async post<T>(path: string, params?: HttpRequestParams, options?: HttpRequestOptions): Promise<HttpResponse<T>> {
if (!this.host) {
throw new Error('Attempting to make network request before host is set')
}
return this.runHttp({
url: joinPaths(this.host, path),
params,
verb: HttpVerb.Post,
authentication: options?.authentication ?? this.getSessionAccessToken(),
customHeaders: options?.headers,
})
}
async put<T>(path: string, params?: HttpRequestParams, options?: HttpRequestOptions): Promise<HttpResponse<T>> {
return this.runHttp({
url: joinPaths(this.host, path),
params,
verb: HttpVerb.Put,
authentication: options?.authentication ?? this.getSessionAccessToken(),
})
}
async patch<T>(path: string, params: HttpRequestParams, options?: HttpRequestOptions): Promise<HttpResponse<T>> {
return this.runHttp({
url: joinPaths(this.host, path),
params,
verb: HttpVerb.Patch,
authentication: options?.authentication ?? this.getSessionAccessToken(),
})
}
async delete<T>(path: string, params?: HttpRequestParams, options?: HttpRequestOptions): Promise<HttpResponse<T>> {
return this.runHttp({
url: joinPaths(this.host, path),
params,
verb: HttpVerb.Delete,
authentication: options?.authentication ?? this.getSessionAccessToken(),
})
}
async runHttp<T>(httpRequest: HttpRequest): Promise<HttpResponse<T>> {
if (this.__latencySimulatorMs) {
await sleep(this.__latencySimulatorMs, true)
}
httpRequest.params = httpRequest.params
? this.params(httpRequest.params as Record<string | number | symbol, unknown>)
: undefined
const isRefreshRequest = httpRequest.url === joinPaths(this.host, Paths.v1.refreshSession)
if (this.inProgressRefreshSessionPromise && !isRefreshRequest) {
await this.inProgressRefreshSessionPromise
httpRequest.authentication = this.getSessionAccessToken()
}
const response = await this.requestHandler.handleRequest<T>(httpRequest)
if (this.loggingEnabled && isErrorResponse(response)) {
this.logger.error('Request failed', httpRequest, response)
}
if (response.meta && !httpRequest.external) {
this.updateMetaCallback?.(response.meta)
}
if (response.status === HttpStatusCode.ExpiredAccessToken && !isRefreshRequest && !httpRequest.external) {
if (this.inProgressRefreshSessionPromise) {
await this.inProgressRefreshSessionPromise
} else {
const hasSessionTokenRenewedInBetweenOurRequest = httpRequest.authentication !== this.getSessionAccessToken()
if (!hasSessionTokenRenewedInBetweenOurRequest) {
this.inProgressRefreshSessionPromise = this.refreshSession()
const isSessionRefreshedResultOrError = await this.inProgressRefreshSessionPromise
let isSessionRefreshed = false
if (!isSessionRefreshedResultOrError.isFailed()) {
isSessionRefreshed = !isErrorResponse(isSessionRefreshedResultOrError.getValue())
}
this.inProgressRefreshSessionPromise = undefined
if (!isSessionRefreshed) {
return response
}
}
}
httpRequest.authentication = this.getSessionAccessToken()
return this.runHttp(httpRequest)
}
return response
}
async refreshSession(): Promise<Result<HttpResponse<SessionRefreshResponseBody>>> {
if (!this.session) {
return Result.fail('No session to refresh')
}
if (this.session instanceof LegacySession) {
return Result.fail('Cannot refresh legacy session')
}
const response = await this.post<SessionRefreshResponseBody>(Paths.v1.refreshSession, {
access_token: this.session.accessToken.value,
refresh_token: this.session.refreshToken.value,
})
if (this.__simulateNextSessionRefreshResponseDrop) {
this.__simulateNextSessionRefreshResponseDrop = false
return Result.fail('Simulating a dropped response')
}
if (isErrorResponse(response)) {
return Result.ok(response)
}
if (response.meta) {
this.updateMetaCallback?.(response.meta)
}
const accessTokenOrError = SessionToken.create(
response.data.session.access_token,
response.data.session.access_expiration,
)
if (accessTokenOrError.isFailed()) {
return Result.fail(accessTokenOrError.getError())
}
const accessToken = accessTokenOrError.getValue()
const refreshTokenOrError = SessionToken.create(
response.data.session.refresh_token,
response.data.session.refresh_expiration,
)
if (refreshTokenOrError.isFailed()) {
return Result.fail(refreshTokenOrError.getError())
}
const refreshToken = refreshTokenOrError.getValue()
const sessionOrError = Session.create(accessToken, refreshToken, response.data.session.readonly_access)
if (sessionOrError.isFailed()) {
return Result.fail(sessionOrError.getError())
}
this.setSession(sessionOrError.getValue())
this.refreshSessionCallback(this.session)
return Result.ok(response)
}
private params(inParams: Record<string | number | symbol, unknown>): HttpRequestParams {
const params = {
...inParams,
...{
[ApiEndpointParam.ApiVersion]: this.apiVersion,
},
}
return params
}
}