forked from mobxjs/serializr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
object.ts
65 lines (64 loc) · 2.42 KB
/
object.ts
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
56
57
58
59
60
61
62
63
64
65
import { invariant, isModelSchema, processAdditionalPropArgs } from "../utils/utils"
import getDefaultModelSchema from "../api/getDefaultModelSchema"
import serialize from "../core/serialize"
import { deserializeObjectWithSchema } from "../core/deserialize"
import { ClazzOrModelSchema, AdditionalPropArgs, PropSchema } from "../api/types"
/**
* `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 to be used to (de)serialize the object
* @param additionalArgs optional object that contains beforeDeserialize and/or afterDeserialize handlers
*/
export default function object(
modelSchema: ClazzOrModelSchema<any>,
additionalArgs?: AdditionalPropArgs
): PropSchema {
invariant(
typeof modelSchema === "object" || typeof modelSchema === "function",
"No modelschema provided. If you are importing it from another file be aware of circular dependencies."
)
let result: PropSchema = {
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,
undefined
)
}
}
result = processAdditionalPropArgs(result, additionalArgs)
return result
}