Skip to content

Commit

Permalink
docs: Add deserialization fields example
Browse files Browse the repository at this point in the history
  • Loading branch information
ntucker committed Dec 16, 2019
1 parent f192b51 commit 46e0b5e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
8 changes: 7 additions & 1 deletion docs/api/Resource.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,13 @@ don't use constructors.
### static fromJS<T extends typeof Resource>(this: T, props: Partial<AbstractInstanceType<T>>): AbstractInstanceType<T>

This is used to create instances of the `Resource` you defined. Will copy over props provided to
the instance in construction.
the instance in construction, among other things. *Be sure to always call `super.fromJS()` when
overriding.*

Can be useful to override to:

* [Deserialize fields](../guides/network-transform#deserializing-fields)
* Add runtime field validation

## Be sure to always provide:

Expand Down
30 changes: 30 additions & 0 deletions docs/guides/network-transform.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,36 @@ abstract class CamelResource extends Resource {
}
```

## Deserializing fields

In many cases, data sent through JSON is serialized into strings since JSON
only has a few primitive types. Common examples include [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)
for dates or even strings for decimals that require high precision ([floats can be lossy](https://floating-point-gui.de/)).
Keeping data in the serialized form is often fine, especially if it is only being used to
be displayed. However, this is problematic if computations are to be done like adding time to a date
or multiplying two numbers.

In this case override the [fromJS()](../api/resource#static-fromjst-extends-typeof-resourcethis-t-props-partialabstractinstancetypet-abstractinstancetypet)
factory method, transforming the fields you wish to change.

```typescript
class MyResource extends Resource {
readonly createdAt = new Date(0);
// other fields here

/** MyResource factory. Takes an object of properties to assign to MyResource. */
static fromJS<T extends typeof Resource>(
this: T,
props: Partial<AbstractInstanceType<T>>,
) {
return super.fromJS({
...props,
createdAt: props.createdAt ? new Date(props.createdAt) : null,
});
}
}
```

## Name calling

Sometimes an API might change a key name, or choose one you don't like. Of course
Expand Down

0 comments on commit 46e0b5e

Please sign in to comment.