-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.ts
More file actions
54 lines (42 loc) · 1.39 KB
/
base.ts
File metadata and controls
54 lines (42 loc) · 1.39 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
import { type APIRequestContext, request } from '@playwright/test'
import { BASE_URL } from './config.ts'
import { type IFinalizeable } from '../../common/types/finalizable.ts'
import { encodePreferenceHeader } from '../../server/http/preferences.ts'
interface IBaseApiClientOptions {
httpHeaders?: Record<string, string>
}
interface IApiRequestOptions {
rawErrorResponse: boolean
}
const PREFERENCE_HEADER_OPTIONS = { 'data-source': 'mocked' }
export class BaseApiClient implements IFinalizeable {
protected _context: APIRequestContext
static async initialize<ClientT extends BaseApiClient>(options?: IBaseApiClientOptions): Promise<ClientT> {
const context = await request.newContext({
baseURL: BASE_URL,
extraHTTPHeaders: {
prefer: encodePreferenceHeader(PREFERENCE_HEADER_OPTIONS),
...options?.httpHeaders,
},
})
return new this(context) as ClientT
}
protected constructor(context: APIRequestContext) {
this._context = context
}
get(url: string, options?: IApiRequestOptions) {
const reqOptions = options && {
headers: {
prefer: encodePreferenceHeader({
...PREFERENCE_HEADER_OPTIONS,
'error-response': options.rawErrorResponse ? 'raw' : 'translated',
}),
},
}
return this._context.get(url, reqOptions)
}
async reset() {}
async finalize() {
await this._context.dispose()
}
}