-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
optional.ts
33 lines (32 loc) · 1.19 KB
/
optional.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
import { invariant, isPropSchema } from "../utils/utils"
import { _defaultPrimitiveProp, SKIP } from "../constants"
import { PropSchema } from "../api/types"
/**
* Optional indicates that this model property shouldn't be serialized if it isn't present.
*
* @example
* createModelSchema(Todo, {
* title: optional(primitive()),
* })
*
* serialize(new Todo()) // {}
*
* @param propSchema propSchema to (de)serialize the contents of this field
*/
export default function optional(propSchema?: PropSchema | boolean): PropSchema {
propSchema = !propSchema || propSchema === true ? _defaultPrimitiveProp : propSchema
invariant(isPropSchema(propSchema), "expected prop schema as second argument")
const propSerializer = propSchema.serializer
invariant(
typeof propSerializer === "function",
"expected prop schema to have a callable serializer"
)
const serializer: PropSchema["serializer"] = (sourcePropertyValue, key, sourceObject) => {
const result = propSerializer(sourcePropertyValue, key, sourceObject)
if (result === undefined) {
return SKIP
}
return result
}
return Object.assign({}, propSchema, { serializer })
}