src/RawData.ts   A
last analyzed

Complexity

Total Complexity 4
Complexity/F 0

Size

Lines of Code 78
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 8.33%

Importance

Changes 0
Metric Value
wmc 4
eloc 60
mnd 4
bc 4
fnc 0
dl 0
loc 78
ccs 1
cts 12
cp 0.0833
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
rs 10
1
import {getOrElse} from 'fp-ts/lib/Either';
2
import * as t from 'io-ts';
3
import {NumberFromString} from 'io-ts-types/lib/NumberFromString';
4
import {merge} from 'lodash';
5
import {Entity} from './Entity';
6
import {Identifier} from './Identifier';
7
import {JsonApiDataC} from './io/JsonApiDataC';
8
import {ResourceIdentifierC} from './io/ResourceIdentifierC';
9
import {JsonApiData} from './JsonApiData';
10
import {Relationships} from './Relationships';
11
import {ResourceIdentifier} from './ResourceIdentifier';
12
import {ResourceRecord} from './ResourceRecord';
13
import {UnknownRecord} from './UnknownRecord';
14
15
const fromRelationships = (data: Relationships, resources: ResourceRecord): UnknownRecord =>
16
  Object.keys(data)
17
    .reduce(
18
      (relationships: ResourceRecord, key: string) => {
19
        const relationship = data[key];
20
        const strings = key.split('.');
21
22
        return merge(
23
          relationships,
24
          strings.length > 1
25
            ? {
26
              [strings[0]]: fromRelationships(
27
                {[strings.slice(1).join('.')]: relationship},
28
                resources
29
              )
30
            }
31
            : {
32
              [key]: (
33
                t.array(ResourceIdentifierC).is(relationship.data)
34
                  ? relationship.data
35
                    .map(
36
                      identifier => fromJsonApiData(
37
                        resources[ResourceIdentifier.iso.string.get(identifier)],
38
                        resources
39
                      )
40
                    )
41
                  : fromJsonApiData(
42
                  resources[ResourceIdentifier.iso.string.get(relationship.data)],
43
                  resources
44
                  )
45
              )
46
            }
47
        );
48
      },
49
      {}
50
    );
51
52
const fromJsonApiData = (data: JsonApiData, resources: ResourceRecord): UnknownRecord =>
53
  merge(
54
    {
55
      ...(
56
        ResourceIdentifierC.is(data)
57
          ? {
58
            _type: data.type,
59
            _id: getOrElse<unknown, Identifier>(() => data.id)(
60
              NumberFromString.decode(data.id)
61
            )
62
          } as Entity
63
          : null
64
      ),
65
      ...data.attributes
66
    },
67
    fromRelationships(data.relationships || {}, resources)
68
  );
69
70
const fromJson = (u: unknown, resources: ResourceRecord): unknown =>
71 2
  JsonApiDataC.is(u)
72
    ? fromJsonApiData(u, resources)
73
    : u;
74
75
export const RawData = {
76
  fromJson: fromJson
77
};
78