mercredi 31 juillet 2019

How to apply CQS pattern on multiple data sources?

I'm learning the CQS pattern and I'm wondering how to use it on a system that has practically the same data in multiple systems. The systems may be an SQL database or a REST API, or some other system. But the data is almost the same regardless of the system (some may have less fields than others).

How would you implement a command that creates a new data entity called "device"? There's a Device table in the SQL database and a REST API that accepts a json with device-related data.

I would imagine there would be a SaveDeviceCommand which has one public property DeviceDto (which contains the data to be saved).

The we would have the result for the command (which in this case is only the ID of the newly created device). I know that strictly speaking a command should not return any values, but here I'm willing to bend that rule a bit.

Lastly we would need to implement the CommandHandlers that do that actual work, right? We would implement CreateNewDeviceToDatabaseCommandHandler and CreateNewDeviceToRestServiceCommandHandler. Quite long names I think.

Is there any more elegant way to do this? One command per data storage because we need a data context (e.g. EntityFramework DbContext) for the command handler to actually be able to make the save?

public class SaveDeviceToDatabaseCommandHandler : ICommandHandler<SaveDeviceCommand, SaveDeviceCommandResult>
{
    private readonly ICommandHandler<SaveDeviceCommand, SaveDeviceCommandResult> _saveDeviceCommand;
    private readonly DeviceContext _deviceContext;

    public SaveDeviceToDatabaseCommandHandler(ICommandHandler<SaveDeviceCommand, SaveDeviceCommandResult> saveDeviceCommand,
                                              DeviceContext deviceContext)
    {
        _saveDeviceCommand = saveDeviceCommand;
        _deviceContext = deviceContext;
    }

    public Task<SaveDeviceCommandResult> HandleAsync(SaveDeviceCommand command)
    {
        // Implementation for the entity framework
    }
}

Aucun commentaire:

Enregistrer un commentaire