yesodweb / yesodweb/persistent

Support `HasFieldDict` as in `prairie`

Open
#1,389 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Haskell
Stars
486
Forks
306
PR merge metrics
No merged PRs in 30d

Description

prarie has a type class called FieldDict which is super useful for doing record metaprogramming, especially with tabulateRecordA etc.

Example use is to derive FromJSON for a Record rec => rec provided that all the fields have FromJSON instances:

newtype RecordJSON a = RecordJSON a

instance (FieldDict FromJSON a) => FromJSON (RecordJSON a) where
    parseJSON = RecordJSON <$> withObject "RecordJSON" \o -> do
        tabulateRecordA \field ->
            withFieldDict @FromJSON field do
                o .: recordFieldLabel field

instance (FieldDict ToJSON a) => ToJSON (RecordJSON a) where
    toJSON (RecordJSON a) =
        object $
            map mkObjectEntry allFields
      where
        mkObjectEntry (SomeField f) = 
            ( recordFieldLabel f
            , withFieldDict @ToJSON field $ toJSON $ getField f a)
            )

This is coming up as particularly useful in the esqueleto library, where we'd like to provide JSON encoders/decoders that use the database field names for how an entity is encoded, rather than the Haskell names.

Bikeshedding on the name I think it's probably clearer as:

class Record rec => ConstrainedFields (c :: Type -> Constraint) rec where
    getFieldConstraint :: Field rec a -> Dict (c a)

withFieldInstance :: forall c rec r. ConstrainedFields c rec => Field rec a -> (c a => r) -> r

Docs can mostly be copied over from the prairie library, and eventually we'll be able to use it directly.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading prairie’s FieldDict documentation and comparing its FieldDict, withFieldDict, and tabulateRecordA APIs with the proposed ConstrainedFields interface. The issue names no persistent source file or test; done means exposing equivalent record field-constraint support, documenting it, and confirming it enables the described database-field-name JSON use case in esqueleto.

Written by the indexing model from the issue text.

Assessment

Tech stack
haskell
Domain
backend-api-design, databases
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.