r/fsharp•
trents92

DDD and the UI layer

Hi everyone,

I wanted to get some insight from those that write server code in a DDD style and use that code on the front end. I like the concept of the front and backend sharing validation, but my backend has been written in such a way that it accepts json, validates the json, and turns it into domain types. For example:

type NonEmptyString100 = private NonEmptyString100 of string

Specifies a string that cannot be empty and max 100 characters.

I wanted to share this on the front end, but I have run into issues where the domain types do not translate well into the corresponding datatypes without constantly unwrapping and rewrapping. For example, a textbox value.

Is this an easy fix or should I separate the validation from the translation steps?

Posted Sep 3, 2020, 1:04 AM UTC

53
NihilCredo•

There's several good reasons to duplicate your types in two versions:

  • An internal, 'smart' domain model using unions, private constructors, and all that good stuff to ensure illegal states are not representable
  • A public, 'dumb' DTO that's serialization-friendly and uses only the least common denominator of features among your clients

One reason is, as you've found, to avoid problems with mapping and unmapping to view models or JSON payloads.

Another, just as big, is that you are able to tweak and update a single domain model without causing breaking changes in your DTO. A third, related to the second, is that you can now support versioned APIs by adding new versions of DTOs for each new endpoint, while your actual code works with a single up-to-date domain model.

And a fourth is that you now have the freedom to decouple the message types from the model types, so you can design free RPC calls instead of sticking to a REST-ish model where you send updated entities.

Once you have the two sets of types, if you are returning a DTO as an output, you just need a (model -> dto) function. If you're taking it in as an input, you want a (dto -> result<model, validationError list>).

There are two situations where I would consider not duplicating the type:

  • When you you're going full-stack F#, be it with Fable, Websharper, Bolero, or whatnot. In that case you can happily reuse the same types, being aware that your frontend and backend will be very tightly coupled and should be deployed as a single entity and you will not be able to call the same endpoints from multiple frontends (eg. web app + native client) unless they are all written in F#.

  • When you're going full-in on your web framework's native validation tools - in the case of ASP.NET Core, you're supposed to have dumb unsafe C#-style classes, and then decorate then with validation attributes such as [<MaxLength 100>]. This has a significant upside in that you don't need to actually write the validation code, the framework will automatically return a pretty good HTTP 400 error message saying stuff like 'The name field should not be longer than 100 characters'.

2
absolutejam•

If you're using specific types like that (which I think is great), I'd take the approach as advertised by Scott W and ensure all of your types have a toDomain and fromDomain static method. I do this and have the toDomain return a Validatable<'t> (more info below).

I'm working through this right now on a side project. It's all very much a work in progress, but the pattern I've currently settled on is:

  • A shared Validation module (Part of my app's Core, so it's used by the server, client and any other apps)
  • All of my domain types implement an IValidatable interface which is a single method that returns a Validatable<'t> (All part of the shared Validation module)
  • Any form records consist of fields that are Validatable<'t> where 't is my domain type, eg.
  • On field debounce (Thoth.Elmish.Debouncer), I validate the affected field via. the IValidatable interface and show any errors to the user. The submit button is not enabled until all form fields are valid.
  • On form submit, I validate the entire form object and if it passes, I convert to the appropriate DTO record (eg. CreateRealmDto). This is then validated again when the backend receives it (the frontend is not trusted).
  • I'm currently planning on only validating things like uniqueness of a field (eg. if another instance exists with the same name) on submitting the form to limit backend involvement, but this could change. This is handled by the command handler service for that aggregate.
  • All errors from the API (Fable.Remoting) are handled before being sent back to the end-user and logged, then converted to a PropagatedError which is a discriminated union of available errors, which currently consists of:

​

type PropagatedError =
| Validation of ValidationError list
| InvalidChange of message: string
| AlreadyExists of message: string
| UnspecifiedError // anything exceptional, that the end-user doesn't need to know

My Validation module is here: https://paste.ee/p/LCDSe (Again, very much WIP)

​

EDIT: Anyone know a good place to paste F# snippets?!

1