CQRS Event Sourcing: Validate UserName uniqueness

前端 未结 8 1241
醉话见心
醉话见心 2021-01-29 18:08

Let\'s take a simple \"Account Registration\" example, here is the flow:

  • User visit website
  • Click \"Register\" button and fill form, click \"Save\" button
8条回答
  •  礼貌的吻别
    2021-01-29 18:40

    Like many others when implementing a event sourced based system we encountered the uniqueness problem.

    At first I was a supporter of letting the client access the query side before sending a command in order to find out if a username is unique or not. But then I came to see that having a back-end that has zero validation on uniqueness is a bad idea. Why enforce anything at all when it's possible to post a command that would corrupt the system ? A back-end should validate all it's input else you're open for inconsistent data.

    What we did was create an index table at the command side. For example, in the simple case of a username that needs to be unique, just create a user_name_index table containing the field(s) that need to be unique. Now the command side is able to query a username's uniqueness. After the command has been executed it's safe to store the new username in the index.

    Something like that could also work for the Order discount problem.

    The benefits are that your command back-end properly validates all input so no inconsistent data could be stored.

    A downside might be that you need an extra query for each uniqueness constraint and you are enforcing extra complexity.

提交回复
热议问题