-
Notifications
You must be signed in to change notification settings - Fork 97
/
rest-adapter.ts
85 lines (73 loc) · 2.18 KB
/
rest-adapter.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
import axios from 'axios'
import { AxiosInstance, createHttpClient, CreateHttpClientParams } from 'contentful-sdk-core'
import copy from 'fast-copy'
import { Adapter, MakeRequestOptions } from '../../common-types'
import endpoints from './endpoints'
export type RestAdapterParams = CreateHttpClientParams & {
/**
* Contentful CMA Access Token
*/
accessToken: CreateHttpClientParams['accessToken']
/**
* API host
* @default api.contentful.com
*/
host?: string
/**
* direct file upload host
* @default upload.contentful.com
*/
hostUpload?: string
}
export const defaultHostParameters = {
defaultHostname: 'api.contentful.com',
defaultHostnameUpload: 'upload.contentful.com',
}
export class RestAdapter implements Adapter {
private readonly params: RestAdapterParams
public constructor(params: RestAdapterParams) {
if (!params.accessToken) {
throw new TypeError('Expected parameter accessToken')
}
this.params = {
...defaultHostParameters,
...copy(params),
}
}
public async makeRequest<R>({
entityType,
action: actionInput,
params,
payload,
headers,
userAgent,
}: MakeRequestOptions): Promise<R> {
// `delete` is a reserved keyword. Therefore, the methods are called `del`.
const action = actionInput === 'delete' ? 'del' : actionInput
const endpoint: (
http: AxiosInstance,
params?: Record<string, unknown>,
payload?: Record<string, unknown>,
headers?: Record<string, unknown>
) => Promise<R> =
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
endpoints[entityType]?.[action]
if (endpoint === undefined) {
throw new Error('Unknown endpoint')
}
const requiredHeaders = {
'Content-Type': 'application/vnd.contentful.management.v1+json',
'X-Contentful-User-Agent': userAgent,
}
// TODO: maybe we can avoid creating a new axios instance for each request
const axiosInstance = createHttpClient(axios, {
...this.params,
headers: {
...requiredHeaders,
...this.params.headers,
},
})
return await endpoint(axiosInstance, params, payload, headers)
}
}