File size: 1,615 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { AxiosResponse } from 'axios'

import { ActionResponse } from '../../../backend/index.js'
import { DifferentActionParams } from '../../hooks/index.js'
import { ApiClient } from '../../utils/index.js'
import { ActionJSON } from './action-json.interface.js'

const api = new ApiClient()

export function callActionApi<K extends ActionResponse>(
  action: ActionJSON,
  params: DifferentActionParams,
  search?: Location['search'],
): Promise<AxiosResponse<K>> {
  let promise: Promise<AxiosResponse<K>>
  const { recordId, recordIds, resourceId } = params

  /* Temporary workaround to avoid breaking changes.
    TODO: For v8 release, rewrite actions to support PUT & DELETE methods.
    Actions should have an option to configure a default method for action buttons. */
  let method = 'get'
  if (action.name === 'delete') {
    method = 'post'
  }

  switch (action.actionType) {
  case 'record':
    if (!recordId) {
      throw new Error('You have to specify "recordId" for record action')
    }
    promise = api.recordAction({
      resourceId, actionName: action.name, recordId, search, method,
    }) as any
    break
  case 'resource':
    promise = api.resourceAction({
      resourceId, actionName: action.name, method,
    }) as any
    break
  case 'bulk':
    if (!recordIds) {
      throw new Error('You have to specify "recordIds" for bulk action')
    }
    promise = api.bulkAction({
      resourceId, actionName: action.name, recordIds, search, method,
    }) as any
    break
  default:
    throw new Error('"actionType" should be either record, resource or bulk')
  }
  return promise
}