-
-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #104 from pyrogenic/skip_undefined
Support optional properties
- Loading branch information
Showing
5 changed files
with
104 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { invariant, isPropSchema } from "../utils/utils" | ||
import { _defaultPrimitiveProp, SKIP } from "../constants" | ||
|
||
/** | ||
* Optional indicates that this model property shouldn't be serialized if it isn't present. | ||
* | ||
* @example | ||
* createModelSchema(Todo, { | ||
* title: optional(primitive()), | ||
* }); | ||
* | ||
* console.dir(serialize(new Todo())); | ||
* // {} | ||
* | ||
* @param {PropSchema} propSchema propSchema to (de)serialize the contents of this field | ||
* @returns {PropSchema} | ||
*/ | ||
export default function optional(name, 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") | ||
function serializer(...args) { | ||
const result = propSerializer(...args) | ||
if (result === undefined) { | ||
return SKIP | ||
} | ||
return result | ||
} | ||
return Object.assign({}, propSchema, {serializer}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters