File size: 1,504 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
import { BaseResource } from '../../backend/adapters/resource/index.js'
import { flat } from '../flat/index.js'
import { convertNestedParam } from './convert-nested-param.js'
import { convertParam } from './convert-param.js'

const prepareParams = (
  params: Record<string, any>,
  resource: BaseResource,
): Record<string, any> => {
  const properties = resource.properties()
  const preparedParams: Record<string, any> = {}

  for (const property of properties) {
    let param = flat.get(params, property.path())
    const key = property.path()
    const propertyDecorator = resource._decorated?.properties[key].toJSON()

    // eslint-disable-next-line no-continue
    if (param === undefined || param === null) continue

    if (property.type() !== 'mixed') {
      if (propertyDecorator?.isArray) {
        preparedParams[key] = param.map((p) => convertParam(p, property.type()))
      } else {
        preparedParams[key] = convertParam(param, property.type())
      }
    } else {
      if (param !== null && propertyDecorator?.subProperties.length) {
        const { subProperties } = propertyDecorator
        for (const subProperty of subProperties) {
          if (propertyDecorator.isArray) {
            param = param.map((p) => convertNestedParam(p, subProperty))
          } else {
            param = convertNestedParam(param, subProperty)
          }
        }
      }

      preparedParams[key] = param
    }
  }

  return { ...params, ...preparedParams }
}

export { prepareParams }