Dynamically Typed Map Extension for Serialzr

Kum Sackey
Frontend Weekly
Published in
2 min readSep 19, 2016

I’ve just finished working with

Michel Weststrate’s library Serialzr, and let me tell you its a great tool to have when building a large SPA with MobX and React.

I ran into a case where I needed a runtime-typed map, and was able to quickly whip up a custom serializr.

In our CMS, users can customize their search results to a great degree, and the backend returns a JSON object containing the search facets and counts.

It looks something like this:

{ 
facets: {
tags: [{
name: “hello_world”, text: “Hello World”, count: 20
}],
resolution: [{
name: “100x100”, text: “Small Screen”, count: 5
}]
}}

We needed to turn that into a map where facet.tags would be an array of TagFacet objects and tag.resolution would be an array of ResolutionFacet objects which have special functionality within the rest of our client interface.

If this were the only time to do it, we’d have simply used createSimpleSchema, but we couldn’t do that because:

  • the facets are dynamically created
  • … and the type of facet is only known at runtime

Serialzr handily has support for custom serialization.

Here’s an example of usage:

import {
serialize,
deserialize,
getDefaultModelSchema,
object,
} from "serializr";
import {typedMap} from "./typed_map";/*** Testing ***/
export class TagFacet {
@serializable name;
@serializable text;
@serializable count;
constructor({name, text, count}){
Object.assign(this, {name, text, count});
}
}
let mapping = {
tags : TagFacet,
default : Object
};
let facetSchema = createSimpleSchema({
name: true, text: true, count: true
});
class FacetContainer {
@serializable(typedMap(list(object(facetSchema)), mapping)) facets;
}
let container = deserialize(getDefaultModelSchema(FacetContainer), {
facets: {
tags: [{
name: "hello_world", text: "Hello World", count: "world"
}],
other: [{
name: "hello_world", text: "Hello World", count: "world"
}]
}
});
console.dir(container, {depth: 3, colors: true});

And here’s the code to run the above example. MIT License.

--

--