Skip to content
Franklin Chieze edited this page Apr 8, 2024 · 3 revisions

A rule is a function that resolves to boolean values and is executed before a repository operation. A resolved value of false means the rule is violated, and the repository operation should not continue.

Rules can be attached to a specific service or to the domain object, in which case they are available to every service in the domain.

import { Domain } from '@datadom/core';

const domain = new Domain();

async function entityMustHaveId(data) {
  return !!(data?.id);
}

domain.addRule('save', entityMustHaveId);

The rule entityMustHaveId will be executed whenever a repository wants to save an entity.

A rule can also return a string type, in which case the returned string would represent the error message with which an error must be thrown when the rule fails.

import { Domain } from '@datadom/core';

const domain = new Domain();

async function entityMustHaveId(data) {
  if (data.id === null) {
    return "ID cannot be null";
  } else if (typeof data.id === "undefined") {
    return "ID cannot be undefined";
  } else if (typeof data.id === "number" && data.id <= 0) {
    return "ID cannot be less than or equal to zero";
  } else if (typeof data.id === "string" && data.id.trim() === "") {
    return "ID cannot be an empty string";
  }

  return true;
}

domain.addRule('save', entityMustHaveId);
Clone this wiki locally