This module contains several miscellaneous functions that can be used with values of any type.
| Function | Description |
|---|---|
.chain() | Allows an anonymous function to be called on a value |
value::diff() | Returns the operation required for one value to equal another |
value::expect() | Returns the current value if the closure that captures it returns a value of true |
value::patch() | Applies JSON Patch operations to a value |
.chain()
The .chain() method passes a value into a closure through which an operation can be performed to return any value.
The output of this function is usually based on the value passed into the closure, but can be something else entirely.
The function is only called using the . operator (method syntax) and, as the name implies, works well within a chain of methods.
For a similar function that allows using a closure on each item in an array instead of a value as a whole, see array::map.
value::diff
The value::diff function returns an object that shows the JSON Patch operation(s) required for the first value to equal the second one.
The following is an example of the value::diff function used to display the changes required to change one string into another. Note that the JSON Patch spec requires an array of objects, and thus an array will be returned even if only one patch is needed between two values.
An example of the output when the diff output includes more than one operation:
value::expect
The value::expect function returns the original value if the closure it is passed into matches a certain condition, and an error otherwise.
This function uses the original value as the first argument. If the original closure returns true, the original value is returned.
A user-defined error string can added after the closure if more context is desired.
This method is most conveniently used when chaining methods to make assertions about the data before it reaches the end of the chain.
As closures in SurrealDB take ownership of the values of their arguments, this function clones the original value in order to return it. It is thus only recommended to use when debugging or when the assertion is a simple one.
value::patch
The value::patch function applies an array of JSON Patch operations to a value. Patches produced by value::diff() round-trip correctly, including when the value is a top-level scalar (the empty path "" refers to the root value per RFC 6901).
For copy and move operations, the from pointer must be a non-empty JSON Pointer; an empty from is rejected at parse time.