File size: 1,932 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { ActionRequest } from '../../actions/index.js'
import { BaseResource } from '../../adapters/index.js'
import {
  FORM_VALUE_NULL,
  FORM_VALUE_EMPTY_OBJECT,
  FORM_VALUE_EMPTY_ARRAY,
} from '../../../frontend/hooks/use-record/params-to-form-data.js'

/**
 * Takes the original ActionRequest and convert string values to a corresponding
 * types. It
 *
 * @param {ActionRequest} originalRequest
 * @param {BaseResource}  resource
 * @returns {ActionRequest}
 *
 * @private
 */
export const requestParser = (
  originalRequest: ActionRequest,
  resource: BaseResource,
): ActionRequest => {
  const { payload: originalPayload } = originalRequest

  const payload = Object.entries(originalPayload || {}).reduce((memo, [path, formValue]) => {
    const property = resource._decorated?.getPropertyByKey(path)

    let value = formValue
    if (formValue === FORM_VALUE_NULL) { value = null }
    if (formValue === FORM_VALUE_EMPTY_OBJECT) { value = {} }
    if (formValue === FORM_VALUE_EMPTY_ARRAY) { value = [] }

    if (property) {
      if (property.type() === 'boolean') {
        if (value === 'true') {
          memo[path] = true
          return memo
        }
        if (value === 'false') {
          memo[path] = false
          return memo
        }
        if (value === '') {
          memo[path] = false
          return memo
        }
      }
      if (['date', 'datetime'].includes(property.type())) {
        if (value === '' || value === null) {
          memo[path] = null
          return memo
        }
      }
      if (property.type() === 'string') {
        const availableValues = property.availableValues()
        if (availableValues && !availableValues.includes(value) && value === '') {
          memo[path] = null
          return memo
        }
      }
    }

    memo[path] = value

    return memo
  }, {})

  return {
    ...originalRequest,
    payload,
  }
}

export default requestParser