« get me outta code hell

serialize.js « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/serialize.js
blob: 2ecbf76c8961df940189015adb2b6e15b4c15604 (plain)
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
// serialize.js: simple interface and utility functions for converting
// Things into a directly serializeable format

// Utility functions

export function id(x) {
  return x;
}

export function toRef(thing) {
  return thing?.constructor.getReference(thing);
}

export function toRefs(things) {
  return things?.map(toRef);
}

export function toContribRefs(contribs) {
  return contribs?.map(({artist, annotation}) => ({
    artist: toRef(artist),
    annotation,
  }));
}

export function toCommentaryRefs(entries) {
  return entries?.map(({artist, ...props}) => ({artist: toRef(artist), ...props}));
}

// Interface

export const serializeDescriptors = Symbol();

export function serializeThing(thing) {
  const descriptors = thing.constructor[serializeDescriptors];

  if (!descriptors) {
    throw new Error(`Constructor ${thing.constructor.name} does not provide serialize descriptors`);
  }

  return Object.fromEntries(
    Object.entries(descriptors)
      .map(([property, transform]) => [property, transform(thing[property])])
  );
}

export function serializeThings(things) {
  return things.map(serializeThing);
}