@abneroliveira/business-rules-engine 中文文档教程

发布于 8年前 浏览 30 项目主页 更新于 3年前

Business rules engine

logo

业务规则引擎是一个轻量级的JavaScript库,用于轻松定义产品、合约的业务规则,表单等

Key features

。主要的好处是业务规则引擎与 HTML DOM 或任何其他 UI 框架不紧密。 此验证引擎与 UI 无关,这就是为什么它可以用作产品、合同等的业务规则的独立表示。 它可以很容易地被不同类型的应用程序、库重用。

  • It enables to decorate custom objects and its properties with validation rules.
  • It supports declarative and imperative validation rules definition
  • It supports composition of validation rules, that enables to validate custom object with nested structures.
  • It is ease to create your own custom validators.
  • It supports asynchronous validation rules (uses promises).
  • It supports shared validation rules.
  • It supports assigning validation rules to collection-based structures - arrays and lists.
  • It supports notification of errors changed via ErrorChanged dispatch event.
  • It supports dot syntax to access to nested rules.
  • It supports localization of error messages with TranslateArgs.
  • It deploys as AMD, CommonJS or plain script module pattern.
  • It offers basic build-in constrains validators. See list basic build-in constraints
  • Other custom validators can be find in extensible repository of custom validators (work in progress).

Installation

此模块已安装:

  • Node.js
  • npm install business-rules-engine
  • use require('business-rules-engine');
  • Bower
  • bower install business-rules-engine
  • Require.js - require(["business-rules-engine/amd/Validation"], …
  • Script tag -> add reference to business-rules-engine/module/Validation.js file.

Example Usage

有 3 种定义验证规则的方法

JSON Schema Validation

    {
        FirstName: {
            type: "string",
            title: "First name",
            required: "true",
            maxLength: 15
        },
        LastName: {
            type: "string",
            "title": "Last name",
            required: true,
            maxLength: 15
        },
        Contacts: {
            type: "array",
            maxItems: 4,
            minItems: 2,
            items: {
                type: "object",
                properties: {
                    Email: {
                        type: "string",
                        title: "Email",
                        default: '',
                        required: true,
                        maxLength: 100,
                        pattern: "S*@S*" },
                    Mobile: {
                        type: "object",
                        properties: {
                            CountryCode: {
                                type: "string",
                                title: "Country code",
                                required: true,
                                maxLength: 3,
                                enum: ["FRA", "CZE", "USA", "GER"]
                            },
                            Number: {
                                type: "string",
                                title: "Phone number",
                                required: true,
                                maxLength: 9
                            }
                        }
                    },
                    FixedLine: {
                        type: "object",
                        properties: {
                            CountryCode: {
                                type: "string",
                                title: "Country code",
                                required: true,
                                maxLength: 3,
                                enum: ["FRA", "CZE", "USA", "GER"]
                            },
                            Number: {
                                type: "string",
                                title: "Phone number",
                                required: true,
                                maxLength: 9
                            }
                        }
                    }
                }
            }
        }
    }
var rules = new FormSchema.JsonSchemaRuleFactory(json).CreateRule("Main");

JSON data annotated with meta data

// define data structure + validation rules meta data
  {
        FirstName: {
            rules: {required: true, maxlength: 15}},
        LastName: {
            rules: {required: true, maxlength: 15}},
        Contacts: [
            {
                Email: {
                    rules: {
                        required: true,
                        maxlength: 100,
                        email: true
                    }
                },
                Mobile: {
                    CountryCode: {
                        rules: {required: true, maxlength: 3, enum: ["FRA", "CZE", "USA", "GER"] }
                    },
                    Number: {
                        rules: {required: true, maxlength: 9 }
                    }
                },
                FixedLine: {
                    CountryCode: {
                        rules: {required: true, maxlength: 3, enum: ["FRA", "CZE", "USA", "GER"] }
                    },
                    Number: {
                        rules: {required: true, maxlength: 9 }
                    }
                }
            },{maxItems: 4, minItems: 2}
        ]
    }
var rules = new FormSchema.JQueryValidationRuleFactory(json).CreateRule("Main");

Imperative definition - using API

要为某些对象定义业务规则,您必须创建抽象验证器。

          //create new validator for object with structure<IPerson>
          var personValidator = new Validation.AbstractValidator();

          //basic validators
          var required = new Validators.RequiredValidator();
          var maxLength = new Validators.MaxLengthValidator(15);

          //assigned validators to property
          personValidator.RuleFor("FirstName", required);
          personValidator.RuleFor("FirstName",maxLength);

          //assigned validators to property
          personValidator.RuleFor("LastName", required);
          personValidator.RuleFor("LastName",maxLength);

          ...

在特定数据上执行它们

          //create test data
          var data = {
                Person1:
                {
                    FirstName:'John',
                    LastName: 'Smith'
                },
                Person2:{}

          }

          //create concrete rule
          var person1Validator = personValidator.CreateRule("Person 1");

          //execute validation
          var result = person1Validator.Validate(this.Data.Person1);

          //verify results
          if (result.HasErrors){
              console.log(result.ErrorMessage);
          }
          //---------
          //--outputs
          //---------

          //create concrete rule
          var person2Validator = personValidator.CreateRule("Person 2");

          //execute validation
          var result = person2Validator.Validate(this.Data.Person1);

           //verify results
          if (result.HasErrors){
              console.log(result.ErrorMessage);
          }

          //---------
          //--outputs
          //---------
          // FirstName: Field is required.
          // LastName: Field is required.

Additional information

Source code

示例 - 带有规则的 .

npm install -g typescript

编译成javascript。

tsc src/validation/Validation.ts --target ES5 --module commonjs

Tests

npm install -g mocha
npm install -g expect.js

运行测试

mocha test

Grunt automatization

Basic steps

  • git clone https://github.com/rsamec/business-rules-engine
  • npm install - get npm packages
  • tsd update - get external typings definition
  • grunt typings - create node-form typings definition - used by custom validators

将所有源构建到 dist 文件夹(生成 AMD、CommonJS 和模块模式)

$ grunt dist

运行代码分析 - complexity + jshint。

$ grunt ci

生成api文档。

$ grunt document

生成类型 -> 打字稿定义文件。

$ grunt typings

运行测试

$ grunt test

Roadmap

Priority

  • Refactor validation API - simplify and better naming
  • Support for changes notification -> partially done, but consider to use framework like ObserveJs or similer notification frameworks
  • Refactor implemenation
    • use depedency injection for managing dependencies among internal components
    • remove depedencies or make them optional - Q, underscore, moment, axiom
    • lazy loading + consider better data structure for composite

Others

  • Add validation groups to shared validation rules
  • Separate ValidationResult from execution of validation rules
  • Improve documentation + more examples

License

The MIT License (MIT)

Business rules engine

logo

Business rules engine is a lightweight JavaScript library for easy business rules definition of the product, the contract, the form etc.

Key features

The main benefit is that business rules engine is not tight to HTML DOM or any other UI framework. This validation engine is UI agnostic and that is why it can be used as an independent representation of business rules of a product, contract, etc. It can be easily reused by different types of applications, libraries.

  • It enables to decorate custom objects and its properties with validation rules.
  • It supports declarative and imperative validation rules definition
  • It supports composition of validation rules, that enables to validate custom object with nested structures.
  • It is ease to create your own custom validators.
  • It supports asynchronous validation rules (uses promises).
  • It supports shared validation rules.
  • It supports assigning validation rules to collection-based structures - arrays and lists.
  • It supports notification of errors changed via ErrorChanged dispatch event.
  • It supports dot syntax to access to nested rules.
  • It supports localization of error messages with TranslateArgs.
  • It deploys as AMD, CommonJS or plain script module pattern.
  • It offers basic build-in constrains validators. See list basic build-in constraints
  • Other custom validators can be find in extensible repository of custom validators (work in progress).

Installation

This module is installed:

  • Node.js
  • npm install business-rules-engine
  • use require('business-rules-engine');
  • Bower
  • bower install business-rules-engine
  • Require.js - require(["business-rules-engine/amd/Validation"], …
  • Script tag -> add reference to business-rules-engine/module/Validation.js file.

Example Usage

There are 3 ways how to define validation rules

JSON Schema Validation

    {
        FirstName: {
            type: "string",
            title: "First name",
            required: "true",
            maxLength: 15
        },
        LastName: {
            type: "string",
            "title": "Last name",
            required: true,
            maxLength: 15
        },
        Contacts: {
            type: "array",
            maxItems: 4,
            minItems: 2,
            items: {
                type: "object",
                properties: {
                    Email: {
                        type: "string",
                        title: "Email",
                        default: '',
                        required: true,
                        maxLength: 100,
                        pattern: "S*@S*" },
                    Mobile: {
                        type: "object",
                        properties: {
                            CountryCode: {
                                type: "string",
                                title: "Country code",
                                required: true,
                                maxLength: 3,
                                enum: ["FRA", "CZE", "USA", "GER"]
                            },
                            Number: {
                                type: "string",
                                title: "Phone number",
                                required: true,
                                maxLength: 9
                            }
                        }
                    },
                    FixedLine: {
                        type: "object",
                        properties: {
                            CountryCode: {
                                type: "string",
                                title: "Country code",
                                required: true,
                                maxLength: 3,
                                enum: ["FRA", "CZE", "USA", "GER"]
                            },
                            Number: {
                                type: "string",
                                title: "Phone number",
                                required: true,
                                maxLength: 9
                            }
                        }
                    }
                }
            }
        }
    }
var rules = new FormSchema.JsonSchemaRuleFactory(json).CreateRule("Main");

JSON data annotated with meta data

// define data structure + validation rules meta data
  {
        FirstName: {
            rules: {required: true, maxlength: 15}},
        LastName: {
            rules: {required: true, maxlength: 15}},
        Contacts: [
            {
                Email: {
                    rules: {
                        required: true,
                        maxlength: 100,
                        email: true
                    }
                },
                Mobile: {
                    CountryCode: {
                        rules: {required: true, maxlength: 3, enum: ["FRA", "CZE", "USA", "GER"] }
                    },
                    Number: {
                        rules: {required: true, maxlength: 9 }
                    }
                },
                FixedLine: {
                    CountryCode: {
                        rules: {required: true, maxlength: 3, enum: ["FRA", "CZE", "USA", "GER"] }
                    },
                    Number: {
                        rules: {required: true, maxlength: 9 }
                    }
                }
            },{maxItems: 4, minItems: 2}
        ]
    }
var rules = new FormSchema.JQueryValidationRuleFactory(json).CreateRule("Main");

Imperative definition - using API

To define business rules for some object, you have to create abstract validator.

          //create new validator for object with structure<IPerson>
          var personValidator = new Validation.AbstractValidator();

          //basic validators
          var required = new Validators.RequiredValidator();
          var maxLength = new Validators.MaxLengthValidator(15);

          //assigned validators to property
          personValidator.RuleFor("FirstName", required);
          personValidator.RuleFor("FirstName",maxLength);

          //assigned validators to property
          personValidator.RuleFor("LastName", required);
          personValidator.RuleFor("LastName",maxLength);

          ...

To use business rules and execute them on particular data

          //create test data
          var data = {
                Person1:
                {
                    FirstName:'John',
                    LastName: 'Smith'
                },
                Person2:{}

          }

          //create concrete rule
          var person1Validator = personValidator.CreateRule("Person 1");

          //execute validation
          var result = person1Validator.Validate(this.Data.Person1);

          //verify results
          if (result.HasErrors){
              console.log(result.ErrorMessage);
          }
          //---------
          //--outputs
          //---------

          //create concrete rule
          var person2Validator = personValidator.CreateRule("Person 2");

          //execute validation
          var result = person2Validator.Validate(this.Data.Person1);

           //verify results
          if (result.HasErrors){
              console.log(result.ErrorMessage);
          }

          //---------
          //--outputs
          //---------
          // FirstName: Field is required.
          // LastName: Field is required.

Additional information

Source code

All code is written in typescript.

npm install -g typescript

To compile to javascript.

tsc src/validation/Validation.ts --target ES5 --module commonjs

Tests

npm install -g mocha
npm install -g expect.js

To run tests

mocha test

Grunt automatization

Basic steps

  • git clone https://github.com/rsamec/business-rules-engine
  • npm install - get npm packages
  • tsd update - get external typings definition
  • grunt typings - create node-form typings definition - used by custom validators

To build all sources to dist folder (generates AMD, CommonJS and module pattern)

$ grunt dist

To run code analyze - complexity + jshint.

$ grunt ci

To generate api documentation.

$ grunt document

To generate typings -> typescript definition files.

$ grunt typings

To run tests

$ grunt test

Roadmap

Priority

  • Refactor validation API - simplify and better naming
  • Support for changes notification -> partially done, but consider to use framework like ObserveJs or similer notification frameworks
  • Refactor implemenation
    • use depedency injection for managing dependencies among internal components
    • remove depedencies or make them optional - Q, underscore, moment, axiom
    • lazy loading + consider better data structure for composite

Others

  • Add validation groups to shared validation rules
  • Separate ValidationResult from execution of validation rules
  • Improve documentation + more examples

License

The MIT License (MIT)

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文