|
1 |
| --- | Codecs that provide forward migrations. In a forward migration, the decoder |
2 |
| --- | migrates to the new format while decoding from JSON and the encoder uses |
3 |
| --- | the new format while encoding to JSON. |
| 1 | +-- | Codecs that provide forward migrations. |
| 2 | +-- | |
| 3 | +-- | In a forward migration, the decoder migrates to the new format while |
| 4 | +-- | decoding from JSON and the encoder uses the new format while encoding to |
| 5 | +-- | JSON. |
4 | 6 | -- |
|
5 | 7 | -- | If you need more control over a forward migration, the `Functor` instance
|
6 | 8 | -- | allows operating on the underlying `Json` value directly.
|
7 | 9 | -- |
|
8 | 10 | -- | If you need both forward and backward migrations, the `Profunctor` instance
|
9 |
| --- | allows operating on the underlying `Json` value directly in both directions. |
| 11 | +-- | allows operating on the underlying `Json` value directly in both |
| 12 | +-- | directions. |
| 13 | +-- | |
| 14 | +-- | Sometimes even greater control over migration is required, and new error |
| 15 | +-- | states need to be introduced. In this situation a `JsonCodec` will need to |
| 16 | +-- | be constructed manually - this should be a last resort though, as building |
| 17 | +-- | a codec manually means there is no guarantee that it will roundtrip |
| 18 | +-- | succesfully. |
| 19 | +-- | |
| 20 | +-- | Migrations are applied by composing a migration codec to run in advance of |
| 21 | +-- | the codec proper. Codec composition is performed with the `(<~<)` and |
| 22 | +-- | `(>~>)` operators from `Data.Codec`. |
| 23 | +-- | |
| 24 | +-- | An example of a codec with a migration applied: |
| 25 | +-- | |
| 26 | +-- | ``` purescript |
| 27 | +-- | import Data.Codec ((>~>)) |
| 28 | +-- | import Data.Codec.Argonaut as CA |
| 29 | +-- | import Data.Codec.Argonaut.Migration as CAM |
| 30 | +-- | import Data.Codec.Argonaut.Record as CAR |
| 31 | +-- | |
| 32 | +-- | type MyModel = { key ∷ String, value ∷ Int } |
| 33 | +-- | |
| 34 | +-- | codec ∷ CA.JsonCodec MyModel |
| 35 | +-- | codec = |
| 36 | +-- | CAM.renameField "tag" "key" >~> |
| 37 | +-- | CA.object "MyModel" (CAR.record |
| 38 | +-- | { key: CA.string |
| 39 | +-- | , value: CA.int |
| 40 | +-- | }) |
| 41 | +-- | ``` |
| 42 | +-- | |
| 43 | +-- | Here we're using the `renameField` migration to rename a property of our |
| 44 | +-- | JSON object from `"tag"` to `"key"`, and then in the codec proper we only |
| 45 | +-- | need to deal with `"key"`. |
| 46 | +-- | |
| 47 | +-- | Multiple migrations can be chained together using the codec composition |
| 48 | +-- | operators. |
10 | 49 | module Data.Codec.Argonaut.Migration
|
11 | 50 | ( addDefaultField
|
12 | 51 | , updateField
|
|
0 commit comments