src/JsonApiData.ts   A
last analyzed

Complexity

Total Complexity 5
Complexity/F 0

Size

Lines of Code 62
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 48
mnd 5
bc 5
fnc 0
dl 0
loc 62
ccs 11
cts 11
cp 1
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
rs 10
1 1
import * as t from 'io-ts';
2
import {NonEmptyString} from 'io-ts-types/lib/NonEmptyString';
3 1
import {ArrayC} from './io/ArrayC';
4 1
import {EntityC} from './io/EntityC';
5
import {JsonApiDataC} from './io/JsonApiDataC';
6
import {Relationships} from './Relationships';
7
import {RelationshipsRecord} from './RelationshipsRecord';
8 1
import {Resource} from './Resource';
9
import {ResourceIdentifier} from './ResourceIdentifier';
10
import {UnknownRecord} from './UnknownRecord';
11
12
export interface JsonApiData extends t.TypeOf<typeof JsonApiDataC> {
13
}
14
15 8
const fromRecord = ({_type, _id, ...attributes}: UnknownRecord, relationships: RelationshipsRecord): JsonApiData =>
16 8
  ({
17
    ...(
18
      EntityC.is({_type, _id})
19
        ? {
20
          type: '' + _type as NonEmptyString,
21
          id: '' + _id as NonEmptyString
22
        }
23
        : null
24
    ),
25
    ...(
26
      Object.keys(attributes).length > 0
27
        ? {attributes}
28
        : null
29
    ),
30
    ...(
31
      Object.keys(relationships).length > 0
32
        ? {
33
          relationships: Object.keys(relationships)
34
            .reduce(
35
              (carry: Relationships, key: string): Relationships => {
36 2
                const resource = relationships[key];
37
38 2
                return {
39
                  ...carry,
40
                  [key]: {
41
                    data: ArrayC<ResourceIdentifier>().is(resource)
42
                      ? resource.map(Resource.lens.identifier.get)
43
                      : Resource.lens.identifier.get(resource)
44
                  }
45
                };
46
              },
47
              {}
48
            )
49
        }
50
        : null
51
    )
52
  });
53
54 1
const fromJson = (u: unknown, relationships: RelationshipsRecord): unknown =>
55 8
  t.UnknownRecord.is(u)
56
    ? fromRecord(u, relationships)
57
    : u;
58
59 1
export const JsonApiData = {
60
  fromJson: fromJson
61
};
62