bogus34/bookshelf-fields

语言: CoffeeScript

git: https://github.com/bogus34/bookshelf-fields

README.md (中文)

书架领域

Bookshelf插件,用于简化模型验证和字段格式转换。

请查看bookshelf-schema - 插件,它可以执行相同的操作!

  • 字段
  • 高级
  • 添加自定义行为
  • 例子

它到底是做什么的

首先,当插入调用db.plugin时,它(重新)定义了几个db.Model方法:

  • validate - 使用CheckIt执行模型验证。它使用实例数组'验证'   字段级验证和数组'model_validations'用于验证整个模型。
  • format / parse - 对于model中定义的每个字段,应用其format / parse方法

然后当字段应用于模型时

  • 将自身存储在模型__meta.fields数组中
  • 可以为model_validations数组的验证添加一些验证规则
  • 定义具有相同名称的属性。默认情况下,此属性仅调用基本集和get   方法。您可以通过传递dont_create_properties:true来阻止创建属性   或create_properties:false到Fields.plugin或作为字段的选项

最后,当调用enable_validation时,它重新定义了模型初始化方法,添加 订阅事件“保存”以执行验证。

基本用法

首先,您需要书架字段并将导出的插件应用于初始化的数据库实例:

Fields = require 'bookshelf-fields'
db.plugin Fields.plugin(options)

现在您已准备好向模型添加字段信息。有两种方法可以做到:with 导出函数'field','fields'和'enableValidation'并用相同的方法混合成一个 模型原型。如果您选择第二种方式,您需要将选项augement_model:true传递给插件。

提供帮助

  • db.Checkit - 用于验证的Checkit模块
  • plugin(options) - 将Fields功能混合到Bookshelf模型中的方法 db.plugin Fields.plugin()
  • enable_validation(model,options) - 实际启用指定模型的验证。选项   存储在Model.prototype.validation_options中,并在应用验证时传递给Checkit。 enable_validation(用户)
  • field(model,field_class,name,options) - 向模型添加字段 field(User,Fields.StringField,'username',{max_length:64})
  • fields(model,field_definitions ...) - 将一堆字段添加到模型中。 field_definitions是一个   或更多数组,如[field_class,name,options]

字段

常见选项

  • 必需:boolean - 必须提供字段而不是空
  • exists:boolean - 字段不能是未定义的
  • 选项:[array或hash] - 字段必须具有提供的值之一 选项可以定义为数组(['foo','bar'])或哈希({foo:'foo description',bar: 栏描述'})。如果使用散列,则将字段值与散列键进行比较。
  • comparator:function - 与选项一起使用以提供自定义相等检查器。 如果fields值是一个对象并且简单的'=='不合适,则很有用。
  • message:用作默认错误消息。
  • label:用作默认字段标签并替换为错误消息。查看tgriesser / checkit了解详情。

StringField

  • min_length | minLength:整数
  • max_length | maxLength:整数

EmailField

StringField,只需检查该值是否与电子邮件地址相似

NumberField

没有任何验证 - 改为使用IntField或FloatField!

  • gt | greater_than | greaterThan:整数
  • gte | greater_than_equal_to | greaterThanEqualTo | min:整数
  • 'lt | less_than | lessThan`:整数
  • lte | less_than_equal_to | lessThanEqualTo |最大值:整数

IntField

NumberField选中为Integer。加载时应用parseInt。

FloatField

NumberField被检查为Float。加载时应用parseFloat。

BooleanField

在解析和格式上将值转换为布尔值。

DateTimeField字段

验证该值是Date还是可以解析为Date的字符串。 在解析和格式上将值转换为Date。

的DateField

具有剥离时间部分的DateTimeField。

JSONField

验证该值是对象还是有效的JSON字符串。 在加载时解析来自JSON的字符串,并在格式化时串行化为JSON。

高级验证

  • 您可以将对象而不是值分配给验证选项: mix_length:{值:10,消息:'{{label}}太短而无效!'} 其他选项将传递给checkit。
  • 您可以使用验证选项将完整的Checkit验证规则添加到字段: @field StringField'用户名',验证:[{rule:'minLength:5'}]

添加自定义行为

您可以为模型数组验证和model_validations添加额外的验证。请确保 你没有丢弃字段添加的验证。如果重新定义初始化方法调用 父对模型保存初始化或管理调用验证方法。您还可以重新定义验证 方法。

例子

CoffeeScript的

Bookshelf = require 'bookshelf'
Fields = require 'bookshelf-fields'

db = Bookshelf.initialize
    client: 'sqlite'
    connection:
        filename: './test.db'

db.plugin Fields.plugin(augement_model: true)

class User extends db.Model
    tableName: 'users'

    @enable_validation()
    @field Fields.StringField, 'username', max_length: 32
    @field Fields.EmailField, 'email'

new User(username: 'bogus', email: 'bogus@test.com').save()
    .otherwise (errors) ->
        console.log errors.toJSON()
        throw errors
    .then (user) ->
        console.log user.id
        console.log user.username # username is a property, calling @get('username') in getter
        console.log user.email

        user.email = 'invalid-email' # calls @set('email', 'invalid-email') in setter

        user.save().otherwise (errors) ->
            console.log errors.toJSON() # { email: 'The email must contain a valid email address' }

JavaScript的

Bookshelf = require('bookshelf');
Fields = require('bookshelf-fields');

var db = Bookshelf.initialize({
    client: 'sqlite',
    connection: { filename: './test.db' }
});

db.plugin(Fields.plugin);

User = db.Model.extend({ tableName: 'users' });
Fields.enable_validation(User);

Fields.fields(User,
    [Fields.StringField, 'username', {max_length: 32}],
    [Fields.EmailField, 'email']
);

new User({username: 'bogus', email: 'bogus@test.com'}).save()
    .otherwise(function(errors) {
        console.log(errors.toJSON());
        throw errors;
    }).then(function(user) {
        console.log(user.id);
        console.log(user.username); // username is a property, calling @get('username') in getter
        console.log(user.email);

        user.email = 'invalid-email'; // calls @set('email', 'invalid-email') in setter

        user.save().otherwise(function(errors) {
            console.log(errors.toJSON()); // { email: 'The email must contain a valid email address' }
        });
});

本文使用googletrans自动翻译,仅供参考, 原文来自github.com

en_README.md

bookshelf-fields

Bookshelf plugin for simpler model validation and field format convertion.

Please look at bookshelf-schema - plugin that does the same and many more!

What exactly it does

First of all when plugged in with call to db.plugin it (re)defines several db.Model methods:

  • validate - perform validation of model with CheckIt. It uses instance array 'validations' for
    field-level validation and array 'model_validations' for validating the whole model.

  • format/parse - for each field defined in model applys its format/parse method

Then when field is applyed to a model it

  • stores the itself in the models __meta.fields array

  • may add some validation rules to validations of model_validations arrays

  • defines property with the same name. By default this property only calls basic set and get
    methods. You may prevent creation of property by passing dont_create_properties: true
    or create_properties: false to Fields.plugin or as an option of the field

And finally when called to enable_validation it redefines models initialize method, adding
subscription to event 'saving' to perform validation.

Basic usage

First you need to require bookshelf-fields and apply exported plugin to an initialized database instance:

Fields = require 'bookshelf-fields'
db.plugin Fields.plugin(options)

Now you are ready to add fields information to models. There are two equivalent ways to do it: with
exported functions 'field', 'fields' and 'enableValidation' and with the same methods, mixed into a
Model prototype. If you choose the second way you need to pass option augement_model: true to plugin.

Provided helpers

  • db.Checkit - Checkit module used for validation

  • plugin(options) - method that mixes Fields functionality into a Bookshelf Model

    db.plugin Fields.plugin()

  • enable_validation(model, options) - actually turn on validation for a specified model. Options
    are stored in Model.prototype.validation_options and passed to Checkit when validation applied.

    enable_validation(User)

  • field(model, field_class, name, options) - add field to a model

    field(User, Fields.StringField, 'username', {max_length: 64})

  • fields(model, field_definitions...) - add a bunch of fields to a model. field_definitions is one
    or more arrays like [field_class, name, options]

Fields

Common options

  • required: boolean - field must be provided and not empty
  • exists: boolean - field must not be undefined
  • choices: [array or hash] - field must have one of provided values

    choices may be defined as an array (['foo', 'bar']) or as a hash ({foo: 'foo description', bar: bar description'}). If hash used then field value is compared with hash keys.

  • comparator: function - used with choices to provide custom equality checker.

    Useful if fields value is an object and simple '==' is not adequate.

  • message: used as a default error message.

  • label: used as a default field label and substituted to error message. Look at tgriesser/checkit for details.

StringField

  • min_length | minLength: integer
  • max_length | maxLength: integer

EmailField

StringField with simple check that value looks like a email address

NumberField

Does no any validation - use IntField or FloatField instead!

  • gt | greater_than | greaterThan: integer
  • gte | greater_than_equal_to | greaterThanEqualTo | min: integer
  • 'lt|less_than|lessThan`: integer
  • lte | less_than_equal_to | lessThanEqualTo | max: integer

IntField

NumberField checked to be Integer. Applys parseInt when loaded.

FloatField

NumberField checked to be Float. Applys parseFloat when loaded.

BooleanField

Casts value to Boolean on parse and format.

DateTimeField

Validates that value is a Date or a string than can be parsed as Date.
Converts value to Date on parse and format.

DateField

DateTimeField with stripped Time part.

JSONField

Validates that value is object or a valid JSON string.
Parses string from JSON when loaded and stringifies to JSON when formatted.

Advanced validation

  • you may assign object instead of value to validation options:

    mix_length: {value: 10, message: '{{label}} is too short to be valid!'}

    Additional options will be passed to checkit.

  • you may add complete Checkit validation rules to field with validations option:

    @field StringField 'username', validations: [{rule: 'minLength:5'}]

Add custom behaviour

You can add extra validations to models arrays validations and model_validations. Just make sure
that you doesn't throw away validations added by fields. If you redefine initialize method call
parent initialize or manage calling validate method on model saving. You can also redefine validate
method.

Examples

coffeescript

Bookshelf = require 'bookshelf'
Fields = require 'bookshelf-fields'

db = Bookshelf.initialize
    client: 'sqlite'
    connection:
        filename: './test.db'

db.plugin Fields.plugin(augement_model: true)

class User extends db.Model
    tableName: 'users'

    @enable_validation()
    @field Fields.StringField, 'username', max_length: 32
    @field Fields.EmailField, 'email'

new User(username: 'bogus', email: 'bogus@test.com').save()
    .otherwise (errors) ->
        console.log errors.toJSON()
        throw errors
    .then (user) ->
        console.log user.id
        console.log user.username # username is a property, calling @get('username') in getter
        console.log user.email

        user.email = 'invalid-email' # calls @set('email', 'invalid-email') in setter

        user.save().otherwise (errors) ->
            console.log errors.toJSON() # { email: 'The email must contain a valid email address' }

javascript

Bookshelf = require('bookshelf');
Fields = require('bookshelf-fields');

var db = Bookshelf.initialize({
    client: 'sqlite',
    connection: { filename: './test.db' }
});

db.plugin(Fields.plugin);

User = db.Model.extend({ tableName: 'users' });
Fields.enable_validation(User);

Fields.fields(User,
    [Fields.StringField, 'username', {max_length: 32}],
    [Fields.EmailField, 'email']
);

new User({username: 'bogus', email: 'bogus@test.com'}).save()
    .otherwise(function(errors) {
        console.log(errors.toJSON());
        throw errors;
    }).then(function(user) {
        console.log(user.id);
        console.log(user.username); // username is a property, calling @get('username') in getter
        console.log(user.email);

        user.email = 'invalid-email'; // calls @set('email', 'invalid-email') in setter

        user.save().otherwise(function(errors) {
            console.log(errors.toJSON()); // { email: 'The email must contain a valid email address' }
        });
});