-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathobject.js
55 lines (54 loc) · 2.24 KB
/
object.js
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
47
48
49
50
51
52
53
54
55
import {invariant, isModelSchema, processAdditionalPropArgs} from "../utils/utils"
import getDefaultModelSchema from "../api/getDefaultModelSchema"
import serialize from "../core/serialize"
import { deserializeObjectWithSchema } from "../core/deserialize"
/**
* `object` indicates that this property contains an object that needs to be (de)serialized
* using its own model schema.
*
* N.B. mind issues with circular dependencies when importing model schema's from other files! The module resolve algorithm might expose classes before `createModelSchema` is executed for the target class.
*
* @example
* class SubTask {}
* class Todo {}
*
* createModelSchema(SubTask, {
* title: true,
* });
* createModelSchema(Todo, {
* title: true,
* subTask: object(SubTask),
* });
*
* const todo = deserialize(Todo, {
* title: 'Task',
* subTask: {
* title: 'Sub task',
* },
* });
*
* @param {ModelSchema} modelSchema to be used to (de)serialize the object
* @param {AdditionalPropArgs} additionalArgs optional object that contains beforeDeserialize and/or afterDeserialize handlers
* @returns {PropSchema}
*/
export default function object(modelSchema, additionalArgs) {
invariant(typeof modelSchema === "object" || typeof modelSchema === "function", "No modelschema provided. If you are importing it from another file be aware of circular dependencies.")
var result = {
serializer: function (item) {
modelSchema = getDefaultModelSchema(modelSchema)
invariant(isModelSchema(modelSchema), "expected modelSchema, got " + modelSchema)
if (item === null || item === undefined)
return item
return serialize(modelSchema, item)
},
deserializer: function (childJson, done, context) {
modelSchema = getDefaultModelSchema(modelSchema)
invariant(isModelSchema(modelSchema), "expected modelSchema, got " + modelSchema)
if (childJson === null || childJson === undefined)
return void done(null, childJson)
return void deserializeObjectWithSchema(context, modelSchema, childJson, done, additionalArgs)
}
}
result = processAdditionalPropArgs(result, additionalArgs)
return result
}