haskell / haskell/aeson

How to use `genericToEncoding` while adding fields

Open
#799 0 comments 4 reactions 0 assignees View on GitHub
Dominant language
Haskell
Stars
1.3k
Forks
336
Avg merge
3d 7h
Merged PRs (30d)
4

Description

Hi,

We have a pattern in an application where we want to benefit from `genericToJSON` and `genericToEncoding` while being able to add static fields (constant values). Those constant fields are not represented in the Haskell types.

E.g.
```haskell
data Foo = {
bar :: Text,
baz :: Bool
}

instance ToJSON Foo where
toJSON = genericToJson ourCustomOptions
toEncoding = genericToEncoding ourCustomOptions
```

As for `toJSON` we manage to add those static fields as such:
```haskell
appendFields :: [(Text, Value)] -> Value -> Value
appendFields keyValue (Object obj) = Object $ H.fromList keyValue <> obj
appendFields _ a = a

instance ToJSON Foo where
toJSON = appendFields [("field1", "some constant text"), ("field2", someConstantValue)] . genericToJSON ourCustomOptions
```

Recently while reading Aeson doc we noticed that implementing `toEncoding` could be a significant perf improvement (and we have a decent amount of (de)serializing happening in our app) so we thought we would also implement `toEncoding`.

The thing is, we do not manage to have an equivalent mechanism for adding static fields. We are aware of `pairs` which converts a `Series` to an `Encoding`, and `Series` being a `Semigroup`, but since `genericToEncoding` returns an `Encoding` instead of a `Series`, it seems to be impossible to add static fields to an `Encoding`.

Is this possible? If so, what's the (most) idiomatic way to do so? Or is our need impossible to combine with `toEncoding`?

Just to clarify: we don't want to manually write `pairs` for all the fields (in my example above, for `bar` and `baz`), our real domain types have many more fields, and we feel that manually writing them would be tedious and error prone.

Thank you!

Contributor guide

Open the contributing guide

Research direction

Start by reading the Aeson documentation and the APIs for genericToEncoding, Encoding, Series, and pairs. Trace how genericToEncoding produces its result and determine whether static fields can be combined without manually encoding every field. Done means documenting or implementing an idiomatic supported approach, with the limitation clearly stated if the combination is not possible.

Written by the indexing model from the issue text.

Assessment

Tech stack
haskell
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.