[Haskell-cafe] Yesos forms and types with foreign keys

fr33domlover fr33domlover at riseup.net
Sat May 14 20:57:30 UTC 2016


I have a question about RESTful web apps in Haskell. I'm using Yesod but I
suppose the same question can apply to any other framework with type safety

Suppose I have entities A and B defined in my Persistent model file. One of A's
fields is a foreign key referring to B. Each A has its own unique B. The
process of creating a new A would be:

1. Set the user a web form via GET
2. Receive for field data via POST
3. Validate the input
4. Insert a new B value to the DB, and get its ID
5. Define an A value which includes that ID as a foreign key, and insert the
   new A value to the DB

In Yesod, If I use a form of type 'AForm A', running the form must return a
complete A value. But when I runFormPost, I don't have the B entity yet so I
don't have an ID for the foreign key! Ideas what I can do:

- Set that field to some dummy value, and override it later when I insert the B
  value and get its ID
- Define a 'NewA' type which has the same fields as A except for that foreign
  key field
- Insert to the DB in the form itself. Define my form as an MForm so that I
  have access to Handler monad and use runDB to insert to the DB right in the
  form itself, i.e. form success means the DB has been updated

I know little about REST common practice but afaik to allow alternative
representations, e.g. a JSON API, my forms need to return entity types, e.g. A
and not some partial NewA. Also my forms so far are all simple AForms which
just do validation, sometimes against the DB, and never insert or delete
anything. Insertion and deletetion I always do in the handlers. The dummy value
may work, I already have one case where I use it, but it's ugly and requires
that I rely on the specific underlying type of the key, e.g. Int64 for
postgresql but could be ByteString for other backends if I ever want to change.
Maybe some 'dummyKey' function could make it prettier, if at all this is a good

What should I do here?

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: not available
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20160514/7f3bd904/attachment.sig>

More information about the Haskell-Cafe mailing list