forked from mobxjs/serializr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deserialize.ts
251 lines (241 loc) · 8.23 KB
/
deserialize.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
* Deserialization
*/
import { invariant, isPrimitive, isModelSchema, parallel, GUARDED_NOOP } from "../utils/utils"
import getDefaultModelSchema from "../api/getDefaultModelSchema"
import { SKIP, _defaultPrimitiveProp } from "../constants"
import Context from "./Context"
import {
ClazzOrModelSchema,
AfterDeserializeFunc,
BeforeDeserializeFunc,
PropSchema,
ModelSchema,
PropDef,
} from "../api/types"
function schemaHasAlias(schema: ModelSchema<any>, name: string) {
for (const key in schema.props) {
const propSchema = schema.props[key]
if (typeof propSchema === "object" && propSchema.jsonname === name) return true
}
return false
}
function deserializeStarProps(
context: Context,
schema: ModelSchema<any>,
propDef: PropDef,
obj: any,
json: any
) {
for (const key in json)
if (!(key in schema.props) && !schemaHasAlias(schema, key)) {
const jsonValue = json[key]
if (propDef === true) {
// when deserializing we don't want to silently ignore 'unparseable data' to avoid
// confusing bugs
invariant(
isPrimitive(jsonValue),
"encountered non primitive value while deserializing '*' properties in property '" +
key +
"': " +
jsonValue
)
obj[key] = jsonValue
} else if (propDef && (!propDef.pattern || propDef.pattern.test(key))) {
propDef.deserializer(
jsonValue,
// for individual props, use root context based callbacks
// this allows props to complete after completing the object itself
// enabling reference resolving and such
context.rootContext.createCallback((r) => r !== SKIP && (obj[key] = r)),
context
)
}
}
}
/**
* Deserializes a json structure into an object graph.
*
* This process might be asynchronous (for example if there are references with an asynchronous
* lookup function). The function returns an object (or array of objects), but the returned object
* might be incomplete until the callback has fired as well (which might happen immediately)
*
* @param schema to use for deserialization
* @param json data to deserialize
* @param callback node style callback that is invoked once the deserialization has
* finished. First argument is the optional error, second argument is the deserialized object
* (same as the return value)
* @param customArgs custom arguments that are available as `context.args` during the
* deserialization process. This can be used as dependency injection mechanism to pass in, for
* example, stores.
* @returns deserialized object, possibly incomplete.
*/
export default function deserialize<T>(
modelschema: ClazzOrModelSchema<T>,
jsonArray: any[],
callback?: (err: any, result: T[]) => void,
customArgs?: any
): T[]
export default function deserialize<T>(
modelschema: ClazzOrModelSchema<T>,
json: any,
callback?: (err: any, result: T) => void,
customArgs?: any
): T
export default function deserialize<T>(
clazzOrModelSchema: ClazzOrModelSchema<T>,
json: any | any[],
callback: (err?: any, result?: T | T[]) => void = GUARDED_NOOP,
customArgs?: any
): T | T[] {
invariant(arguments.length >= 2, "deserialize expects at least 2 arguments")
const schema = getDefaultModelSchema(clazzOrModelSchema)
invariant(isModelSchema(schema), "first argument should be model schema")
if (Array.isArray(json)) {
const items: any[] = []
parallel(
json,
function (childJson, itemDone) {
const instance = deserializeObjectWithSchema(
undefined,
schema,
childJson,
itemDone,
customArgs
)
// instance is created synchronously so can be pushed
items.push(instance)
},
callback
)
return items
} else {
return deserializeObjectWithSchema(undefined, schema, json, callback, customArgs)
}
}
export function deserializeObjectWithSchema(
parentContext: Context<any> | undefined,
modelSchema: ModelSchema<any>,
json: any,
callback: (err?: any, value?: any) => void,
customArgs: any
) {
if (json === null || json === undefined || typeof json !== "object")
return void callback(null, null)
const context = new Context(parentContext, modelSchema, json, callback, customArgs)
const target = modelSchema.factory(context)
// todo async invariant
invariant(!!target, "No object returned from factory")
// TODO: make invariant? invariant(schema.extends ||
// !target.constructor.prototype.constructor.serializeInfo, "object has a serializable
// supertype, but modelschema did not provide extends clause")
context.setTarget(target)
const lock = context.createCallback(GUARDED_NOOP)
deserializePropsWithSchema(context, modelSchema, json, target)
lock()
return target
}
export function deserializePropsWithSchema<T>(
context: Context<T>,
modelSchema: ModelSchema<T>,
json: any,
target: T
) {
if (modelSchema.extends) deserializePropsWithSchema(context, modelSchema.extends, json, target)
function deserializeProp(propDef: PropSchema, jsonValue: object, propName: keyof T) {
const whenDone = context.rootContext.createCallback(
(r) => r !== SKIP && (target[propName] = r)
)
propDef.deserializer(
jsonValue,
// for individual props, use root context based callbacks
// this allows props to complete after completing the object itself
// enabling reference resolving and such
(err: any, newValue: any) =>
onAfterDeserialize(
whenDone,
err,
newValue,
jsonValue,
json,
propName,
context,
propDef
),
context,
target[propName] // initial value
)
}
for (const key of Object.keys(modelSchema.props) as (keyof T)[]) {
let propDef: PropDef = modelSchema.props[key]
if (!propDef) return
if (key === "*") {
deserializeStarProps(context, modelSchema, propDef, target, json)
return
}
if (propDef === true) propDef = _defaultPrimitiveProp
const jsonAttr = propDef.jsonname ?? key
invariant("symbol" !== typeof jsonAttr, "You must alias symbol properties. prop = %l", key)
const jsonValue = json[jsonAttr]
const propSchema = propDef
const callbackDeserialize = (err: any, jsonValue: any) => {
if (!err && jsonValue !== undefined) {
deserializeProp(propSchema, jsonValue, key)
}
}
onBeforeDeserialize(
callbackDeserialize,
jsonValue,
json,
jsonAttr as string | number,
context,
propDef
)
}
}
export const onBeforeDeserialize: BeforeDeserializeFunc = (
callback,
jsonValue,
jsonParentValue,
propNameOrIndex,
context,
propDef
) => {
if (propDef && typeof propDef.beforeDeserialize === "function") {
propDef.beforeDeserialize(
callback,
jsonValue,
jsonParentValue,
propNameOrIndex,
context,
propDef
)
} else {
callback(null, jsonValue)
}
}
export const onAfterDeserialize: AfterDeserializeFunc = (
callback,
err,
newValue,
jsonValue,
jsonParentValue,
propNameOrIndex,
context,
propDef
) => {
if (propDef && typeof propDef.afterDeserialize === "function") {
propDef.afterDeserialize(
callback,
err,
newValue,
jsonValue,
jsonParentValue,
propNameOrIndex,
context,
propDef
)
} else {
callback(err, newValue)
}
}