How to implement domain entity and its business logic for dependent data

Viewed 47

Let's say we have a stations and each station has many station machines and station machine can't exist without the station id. Each machines can have various sockets and each machine is of particular brand. The application needs to create a station and all its dependent machines.

It means we need to create the stationFirst and then pass the machines, however station depends upon machine

Domain Entities Props:

IStationProps {
  name: string;
  machines: Machine[];
  location: string
}

IMachineProps {
   name: string;
   sockets: Socket[],
   
}

ISocket {
   name: string;
}

IBrand {
  name: string
}

If a request contains the socket list which can either be already in system and some which are created at time of station creation.

How to validate the socket if they already exist in the system and if the given id is not valid we need to make it as new entry.

Example

"socket": [
        {
          "socket_id": "some_id",
          "name" : "Alpha" 
        },
        {
         "name": "delta"
        },
        {
         "socket_id": "some_id_which_is_not_in_db"
         name: "gamma"
        }
      ]

Here, after validating all the sockets, second and third socket id need to be also created in the system and also added to the station machine. Similarly with brand.

Also in below code the machines list also need station id to be validated as machine for creation and station need machines as list for creation, how to handle this dependent situation.

const machines = Machines.create(machines_array) 

const station = Station.create({
        name,
        machines 
      });
1 Answers

I would break the problem down into inter-dependencies, for example:

  • A station has many machines
  • A machine has many sockets
  • A socket must have one id

Luckily, there are no circular dependencies between the has many and has one relationships. This means you can build the domain model from the bottom up.

const sockets = Sockets.filter(sockets_array);
const machines = Machines.create(machines_array.map(m => {...m, sockets: sockets}));
const station = Station.create({name, machines});

This is more or less pseudo-code but hopefully you get the idea. Start at the bottom of the relationships, figure out what needs to change, then build up to the top-most parent.

Related