-
Notifications
You must be signed in to change notification settings - Fork 659
/
api-client.ts
273 lines (249 loc) · 7.83 KB
/
api-client.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
271
272
273
import axios, { AxiosResponse, AxiosInstance, AxiosRequestConfig } from 'axios'
import {
ResourceActionParams,
BulkActionParams,
RecordActionParams,
ActionParams,
} from '../../backend/utils/view-helpers/view-helpers.js'
import { RecordJSON } from '../interfaces/index.js'
import { RecordActionResponse, ActionResponse, BulkActionResponse } from '../../backend/actions/action.interface.js'
let globalAny: any = {}
try {
globalAny = window
} catch (error) {
if (!(error instanceof ReferenceError)) {
throw error
} else {
globalAny = { isOnServer: true }
}
} finally {
if (!globalAny) {
globalAny = { isOnServer: true }
}
}
/**
* Type of an [axios request]{@link https://github.com/axios/axios/blob/master/index.d.ts#L43}
*
* @typedef {object} AxiosRequestConfig
* @alias AxiosRequestConfig
* @memberof ApiClient
* @see https://github.com/axios/axios/blob/master/index.d.ts#L43
*/
const checkResponse = (response: AxiosResponse): void => {
if (globalAny.isOnServer) { return }
const loginUrl = [globalAny.location.origin, globalAny.REDUX_STATE.paths.loginPath].join('')
// if response has redirect to loginUrl
if (response.request.responseURL
&& response.request.responseURL.match(loginUrl)
) {
// eslint-disable-next-line no-undef, no-alert
alert('Your session expired. You will be redirected to login screen')
globalAny.location.assign(loginUrl)
}
}
/**
* Extends {@link AxiosRequestConfig}
*
* @alias ActionAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link AxiosRequestConfig}
*/
export type ActionAPIParams = AxiosRequestConfig & ActionParams
/**
* Extends {@link ActionAPIParams}
*
* @alias ResourceActionAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link AxiosRequestConfig}
*/
export type ResourceActionAPIParams = AxiosRequestConfig & ResourceActionParams & {
query?: string;
}
/**
* Extends {@link ActionAPIParams}
*
* @alias RecordActionAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link ActionAPIParams}
*/
export type RecordActionAPIParams = AxiosRequestConfig & RecordActionParams
/**
* Extends {@link ActionAPIParams}
*
* @alias BulkActionAPIParams
* @memberof ApiClient
* @see https://github.com/axios/axios/blob/master/index.d.ts#L43
* @property {any} ... any property supported by {@link ActionAPIParams}
*/
export type BulkActionAPIParams = AxiosRequestConfig & BulkActionParams
/**
* Extends {@link AxiosRequestConfig}
*
* @alias GetPageAPIParams
* @memberof ApiClient
* @property {any} ... any property supported by {@link AxiosRequestConfig}
*/
export type GetPageAPIParams = AxiosRequestConfig & {
/**
* Unique page name
*/
pageName: string;
}
/**
* Client which access the admin API.
* Use it to fetch data from auto generated AdminJS API.
*
* In the backend it uses [axios](https://github.com/axios/axios) client
* library.
*
* Usage:
* ```javascript
* import { ApiClient } from 'adminjs'
*
* const api = new ApiClient()
* // fetching all records
* api.resourceAction({ resourceId: 'Comments', actionName: 'list' }).then(results => {...})
* ```
* @see https://github.com/axios/axios
* @hideconstructor
*/
class ApiClient {
private baseURL: string
private client: AxiosInstance
constructor() {
this.baseURL = ApiClient.getBaseUrl()
this.client = axios.create({
baseURL: this.baseURL,
})
}
static getBaseUrl(): string {
if (globalAny.isOnServer) { return '' }
return [globalAny.location.origin, globalAny.REDUX_STATE?.paths.rootPath].join('')
}
/**
* Search by query string for records in a given resource.
*
* @param {Object} options
* @param {String} options.resourceId id of a {@link ResourceJSON}
* @param {String} options.query query string
* @param {String} options.searchProperty optional property name
*
* @return {Promise<SearchResponse>}
*/
async searchRecords({ resourceId, query, searchProperty }: {
resourceId: string;
query: string;
searchProperty?: string;
}): Promise<Array<RecordJSON>> {
if (globalAny.isOnServer) { return [] }
const actionName = 'search'
const response = await this.resourceAction({
resourceId,
actionName,
query,
...(searchProperty ? { params: { searchProperty } } : undefined),
})
checkResponse(response)
return response.data.records
}
/**
* Invokes given resource {@link Action} on the backend.
*
* @param {ResourceActionAPIParams} options
* @return {Promise<ActionResponse>} response from an {@link Action}
*/
async resourceAction(options: ResourceActionAPIParams): Promise<AxiosResponse<ActionResponse>> {
const { resourceId, actionName, data, query, ...axiosParams } = options
let url = `/api/resources/${resourceId}/actions/${actionName}`
if (query) {
const q = encodeURIComponent(query)
url = [url, q].join('/')
}
const response = await this.client.request({
url,
method: data ? 'POST' : 'GET',
...axiosParams,
data,
})
checkResponse(response)
return response
}
/**
* Invokes given record {@link Action} on the backend.
*
* @param {RecordActionAPIParams} options
* @return {Promise<RecordActionResponse>} response from an {@link Action}
*/
async recordAction(options: RecordActionAPIParams): Promise<AxiosResponse<RecordActionResponse>> {
const { resourceId, recordId, actionName, data, ...axiosParams } = options
const response = await this.client.request({
url: `/api/resources/${resourceId}/records/${recordId}/${actionName}`,
method: data ? 'POST' : 'GET',
...axiosParams,
data,
})
checkResponse(response)
return response
}
/**
* Invokes given bulk {@link Action} on the backend.
*
* @param {BulkActionAPIParams} options
* @return {Promise<BulkActionResponse>} response from an {@link Action}
*/
async bulkAction(options: BulkActionAPIParams): Promise<AxiosResponse<BulkActionResponse>> {
const { resourceId, recordIds, actionName, data, ...axiosParams } = options
const params = new URLSearchParams()
params.set('recordIds', (recordIds || []).join(','))
const response = await this.client.request({
url: `/api/resources/${resourceId}/bulk/${actionName}`,
method: data ? 'POST' : 'GET',
...axiosParams,
data,
params,
})
checkResponse(response)
return response
}
/**
* Invokes dashboard handler.
*
* @param {AxiosRequestConfig} options
* @return {Promise<AxiosResponse<any>>} response from the handler function defined in
* {@link AdminJSOptions#dashboard}
*/
async getDashboard<T = unknown>(options: AxiosRequestConfig = {}): Promise<AxiosResponse<T>> {
const response = await this.client.get('/api/dashboard', options)
checkResponse(response)
return response
}
/**
* Invokes handler function of given page and returns its response.
*
* @param {GetPageAPIParams} options
* @return {Promise<AxiosResponse<any>>} response from the handler of given page
* defined in {@link AdminJSOptions#pages}
*/
async getPage<T = unknown>(options: GetPageAPIParams): Promise<AxiosResponse<T>> {
const { pageName, ...axiosParams } = options
const response = await this.client.request({
url: `/api/pages/${pageName}`,
...axiosParams,
})
checkResponse(response)
return response
}
async refreshToken(data: Record<string, any>) {
const response = await this.client.request({
url: '/refresh-token',
method: 'POST',
data,
})
checkResponse(response)
return response
}
}
export {
ApiClient as default,
ApiClient,
}