« 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: a4206fd0ec1553f7985c0b2f73d179e166ca0009 (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
/** @format */

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