Skip to content

Commit

Permalink
Merge pull request #99 from pyrogenic/jdp_allow_serializing_plain_obj…
Browse files Browse the repository at this point in the history
…ects_by_specifying_constructor

Allow serializing plain objects by specifying constructor.
  • Loading branch information
pyrogenic authored Sep 27, 2019
2 parents c9ac762 + 394f1b5 commit 2022227
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/core/serialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { SKIP, _defaultPrimitiveProp } from "../constants"
* The model schema can be omitted if the object type has a default model schema associated with it.
* If a list of objects is provided, they should have an uniform type.
*
* @param arg1 modelschema to use. Optional
* @param arg1 class or modelschema to use. Optional
* @param arg2 object(s) to serialize
* @returns {object} serialized representation of the object
*/
Expand All @@ -22,8 +22,12 @@ export default function serialize(arg1, arg2) {
return [] // don't bother finding a schema
else if (!schema)
schema = getDefaultModelSchema(thing[0])
else if (typeof schema !== "object")
schema = getDefaultModelSchema(schema)
} else if (!schema) {
schema = getDefaultModelSchema(thing)
} else if (typeof schema !== "object") {
schema = getDefaultModelSchema(schema)
}
invariant(!!schema, "Failed to find default schema for " + arg1)
if (Array.isArray(thing))
Expand Down
33 changes: 33 additions & 0 deletions test/classes.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,42 @@ test("schema's can be defined on constructors", t => {
t2.equal(todos.length, 2)
t2.deepEqual(_.serialize(todos), jsonlist)

test("may be used to serialize plain objects", t3 => {
jsonlist[0].otherProp = "should not serialize"
jsonlist[1].otherProp = "should not serialize"

t3.throws(() => {
_.serialize(jsonlist);
}, /Failed to find default schema/)

_.serialize(Todo, jsonlist).forEach((serialized, i) => {
t.equal(serialized.title, jsonlist[i].title)
t.equal(serialized.otherProp, undefined)
})
t3.end()
})

t2.end()
})

test("may be used to serialize plain objects", t2 => {
var source2 = {
title: "test",
otherProp: "should not serialize"
};
t2.throws(() => {
_.serialize(source2);
}, /Failed to find default schema/)

t.deepEqual(_.serialize(Todo, source2), json)
var res2 = _.deserialize(Todo, json)
t.equal(res2.title, "test")
t.equal(res2.otherProp, undefined)
t.equal(res2 instanceof Todo, true)

t2.end()
});

t.end()
})

Expand Down

0 comments on commit 2022227

Please sign in to comment.