« 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: 52aacb074a3b63822ffd543edff078dec24011b2 (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
// 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(({who, what}) => ({who: toRef(who), what}));
}

// 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);
}