« get me outta code hell

simple data serialization & random pages fixes - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/serialize.js
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2022-03-12 19:07:22 -0400
committer(quasar) nebula <qznebula@protonmail.com>2022-03-12 19:07:22 -0400
commit6a86a6aca6215cb4d464b814c34233b001575cd9 (patch)
treecfa90beb1027beda33b4f37c0883bfc99e2d3fad /src/data/serialize.js
parentf27c98a228847d5f300a2d3c1252294d673b639e (diff)
simple data serialization & random pages fixes
Diffstat (limited to 'src/data/serialize.js')
-rw-r--r--src/data/serialize.js38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/data/serialize.js b/src/data/serialize.js
new file mode 100644
index 00000000..9d4e8885
--- /dev/null
+++ b/src/data/serialize.js
@@ -0,0 +1,38 @@
+// 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);
+}