简体   繁体   中英

How to Put Validation Rules in Repository

I have this entity which includes the validation rules. It works. But it seems that maybe the Entity is not the best place to store such rules, because if I have a list of 100 entities, that code is run 100 times which seems unnecessary.

So it seems to me that a better place to keep the rules is in the repository. I have a repository for each entity, and it is a singleton.

But the question is how to do that?

import { type, Entity, validatedResource, association, resource, repository } from 'aurelia-orm';
import { ValidationRules } from 'aurelia-validation';
import { InviteRepository } from 'data/service/invite-repository';
import { autoinject } from 'aurelia-framework';
import { autoinject } from 'aurelia-framework';


@resource()
@repository(InviteRepository)
@validatedResource()
@autoinject()
export class Invite extends Entity {
repository: any;

    id: number;
    firstName = null;
    lastName = null;
    email = null;
    message = null;
    invitedOn: Date;

    constructor() {
        super();

        ValidationRules
            .ensure('firstName').required().satisfies(
                (value)=> this.validateFirstName(value)
            ).withMessage("First Name must be Greg")
            .ensure('lastName').required()
            .ensure('email').email()
            .on(Invite);
    }

    validateFirstName(name: string): boolean {
        return this.getRepository().validateFirstName(this.firstName);
    }

}

There are several kinds of validation to consider.

First is formal validation that has to be met for any entity or value to even be processed. Like "field name is required in this fieldset". Or "name must be not empty". And so on. This validation logic belongs to factories or entity/value constructors and doesn't need external calls.

Another type is checking business rules with regards to the current state of the system. For example "you cannot add routing rule that would make routing ambigous". You can put this logic inside domain services, if it involves more than a single entity/aggregate. Or you can put it in entity, provided that you call it from application layer with all needed external data at hand to make up a validation decision.

At last, there are rules at the DB level that are meant to preserve data consistency. These match naturally to DB constraints and belong to repositories.

So, in your case it seemes to be OK to put it into an entity constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM