Skip to content

DTO vs Entity

Webber Wang edited this page Sep 20, 2020 · 1 revision

DTO

A Data Transfer Object (DTO) is an intermediary structure for transmitting data. An Entity (or model) will use different DTO's depending on the context.

Base

Our Node Entity is

interface NodeDTO {
  id: string
  type: string
  props: any
  children: Array<NodeDTO>
}

Create

The create DTO are mapped from form objects, and require no ID.

type CreateNodeDTO = Optional<NodeDTO, 'id'> // using utility-types NPM

Update, Query

These will use the same as the base DTO so we'll omit using the type alias.

Delete

Delete only requires the ID, so we'll have something like this

interface DeleteNodeDTO extends HasID {}

Or just use HasID

Classes

Our classes should implement the DTO

class Node implements NodeDTO {
  id: string

  ...
}

Data Normalization

We should make the distinction between input types & working types. In https://github.com/gcanti/io-ts, I denotes input while A denotes working type.

interface NodeDtoI {
  id:? string
  type: string
  props?: any
  children?: Array<NodeDtoI>
}

Notice that only type is required. Some props are required for React components but we'll ignore that for simplicity.

We could have a working type that has optional properties, but it will be better to set a default value so that we don't have to constantly check for existence using the optional chain operator ?.

interface NodeDtoA {
  id: string
  type: string
  props: any
  children: Array<NodeDtoA>
}

io-ts has the concept of an output type (O), which could be different, but in our case we only have 2 distinctions.

Clone this wiki locally