File size: 2,355 Bytes
d9494a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  type ApplicationVariableType,
  type ApplicationVariableValue,
} from '@/application/applicationVariablesType';
import { FieldMetadataType } from '@/types/FieldMetadataType';

export const serializeApplicationVariableValue = (
  value: ApplicationVariableValue | undefined,
  type: ApplicationVariableType = FieldMetadataType.TEXT,
): string => {
  if (value === null || value === undefined) {
    return '';
  }

  switch (type) {
    case FieldMetadataType.BOOLEAN:
      return String(value) === 'true' ? 'true' : 'false';
    case FieldMetadataType.NUMBER:
    case FieldMetadataType.NUMERIC:
      return String(value);
    case FieldMetadataType.ARRAY:
    case FieldMetadataType.MULTI_SELECT:
      if (Array.isArray(value)) {
        return JSON.stringify(value);
      }
      if (typeof value === 'string') {
        try {
          const parsed = JSON.parse(value) as unknown;

          if (Array.isArray(parsed)) {
            return value;
          }
        } catch {}

        return JSON.stringify([value]);
      }

      return JSON.stringify(value);
    case FieldMetadataType.RAW_JSON:
    case FieldMetadataType.RICH_TEXT:
      return typeof value === 'string' ? value : JSON.stringify(value);
    default:
      return typeof value === 'string' ? value : String(value);
  }
};

export const deserializeApplicationVariableValue = (
  value: string,
  type: ApplicationVariableType = FieldMetadataType.TEXT,
): ApplicationVariableValue => {
  if (value === '') {
    return type === FieldMetadataType.ARRAY ||
      type === FieldMetadataType.MULTI_SELECT
      ? []
      : '';
  }

  switch (type) {
    case FieldMetadataType.BOOLEAN:
      return value === 'true';
    case FieldMetadataType.NUMBER:
    case FieldMetadataType.NUMERIC: {
      const parsed = Number(value);

      return Number.isNaN(parsed) ? value : parsed;
    }
    case FieldMetadataType.ARRAY:
    case FieldMetadataType.MULTI_SELECT:
      try {
        const parsed = JSON.parse(value) as unknown;

        return Array.isArray(parsed) ? (parsed as string[]) : [];
      } catch {
        return [];
      }
    case FieldMetadataType.RAW_JSON:
    case FieldMetadataType.RICH_TEXT:
      try {
        return JSON.parse(value) as Record<string, unknown>;
      } catch {
        return value;
      }
    default:
      return value;
  }
};