├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── lib ├── attrs_defs.coffee ├── index.coffee ├── messages.coffee ├── model.coffee ├── model_instance.coffee ├── utils.coffee ├── validators.coffee └── validators │ ├── format.coffee │ ├── length.coffee │ └── presence.coffee ├── module.js ├── package.json └── test ├── mocha.opts ├── test-attributes-tags.coffee ├── test-basic_model.coffee ├── test-conditional_validators.coffee ├── test-custom_validators.coffee ├── test-utils.coffee ├── test.coffee └── validators ├── test-format.coffee ├── test-length.coffee └── test-presence.coffee /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | pids 11 | logs 12 | results 13 | compiled 14 | node_modules 15 | npm-debug.log 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | # test on latest nodejs 0.10 branch 4 | node_js: 5 | - "0.10" 6 | 7 | notifications: 8 | email: 9 | - "asaf000@gmail.com" 10 | 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/asaf/nodejs-model.png?branch=master)](https://travis-ci.org/asaf/nodejs-model) 2 | 3 | # nodejs-model 4 | 5 | Okay, so you have a node app backed with some kind of NoSQL schema-less DB such as CouchDB and it all works pretty well, 6 | 7 | But hey, even though schema-less is very cool and produces fast results, for small apps it may make sense, but as application 8 | code grows bigger and bigger, you will eventually end with low data integrity and things will start to become messy, 9 | 10 | So this is what nodejs-model is for, it is a very minimal, extensible model structure for node, it doesn't dictate any 11 | DB requirements nor hook into it directly, it's just a plain javascript object with some enhanced capabilities for 12 | attributes accessors, validations, tagging and filtering. 13 | 14 | Note: If you are aware of Ruby AcitveObject Validations you will probably find some common parts with the 15 | validation capability of it, But _nodejs-model_ goes much further, read on :-) 16 | 17 | 18 | # Why use nodejs-model? 19 | 20 | If one or more of the bullets below makes sense to you, then you should try nodejs-model. 21 | 22 | * Model attributes: A lightweight javascript model with simple accessors. 23 | * Attribute validations: define validation rules per defined attribute. 24 | * Accessibility via tags: Tag attributes with some labels, then allow retrieving/updating only attributes that matches some tags. 25 | * Events: Events are fired when objects are being created or properties are modified. 26 | * Converters: Simply hook converters into attributes, for example an encryptor converter may attach to the _password_ attribute of a _User_ model to encrypt the user's password immediately after it is set with new value. 27 | 28 | #Installation 29 | 30 | To install nodejs-model, use [npm](http://github.com/isaacs/npm): 31 | 32 | ```bash 33 | $ npm install nodejs-model --save 34 | ``` 35 | 36 | 37 | # Basic Usage 38 | 39 | This is how it works: 40 | 41 | Create a _model_ definition with some validation rules 42 | 43 | ``` javascript 44 | var model = require('nodejs-model'); 45 | 46 | //create a new model definition _User_ and define _name_/_password_ attributes 47 | var User = model("User").attr('name', { 48 | validations: { 49 | presence: { 50 | message: 'Name is required!' 51 | } 52 | } 53 | }).attr('password', { 54 | validations: { 55 | length: { 56 | minimum: 5, 57 | maximum: 20, 58 | messages: { 59 | tooShort: 'password is too short!', 60 | tooLong: 'password is too long!' 61 | } 62 | } 63 | }, 64 | //this tags the accessibility as _private_ 65 | tags: ['private'] 66 | }); 67 | 68 | var u1 = User.create(); 69 | //getters are generated automatically 70 | u1.name('foo'); 71 | u1.password('password'); 72 | 73 | console.log(u1.name()); 74 | //prints _foo_ 75 | 76 | //Invoke validations and wait for the validations to fulfill 77 | u1.validate(function() { 78 | if u1.isValid { 79 | //validated, perform business logic 80 | } else { 81 | //validation failed, dump validation errors to the console 82 | console.log(p1.errors) 83 | } 84 | }); 85 | 86 | //get object as a plain object, ready for JSON 87 | console.log(u1.toJSON()); 88 | //produces: { name: 'foo' } 89 | 90 | //now also with attributes that were tagged with 'private' 91 | console.log(u1.toJSON('private')); 92 | //produces: { name: 'foo' } { password: 'password' } 93 | ``` 94 | 95 | 96 | Simple as that, your model is enhanced with a validate() method, simply invoke it to validate the model object 97 | against the validation rules defined in the schema. 98 | 99 | 100 | # Updating Model Instance 101 | 102 | Assuming you have a simple model instance (`u1` as defined in the basic example above, you can update it with new data 103 | at some point after loading an object from DB / file / JSON / etc: 104 | 105 | 106 | ``` javascript 107 | someObj = { 108 | name: 'bar', 109 | password: 'newpassword' 110 | }; 111 | 112 | u1.update(someObj); 113 | 114 | console.log(u1.name()); 115 | //prints bar 116 | console.log(u1.password()); 117 | //NOTE: prints password 118 | ``` 119 | 120 | Pay attention that password wasn't updated, this is because when invoking `update(object)` only public attributes (any 121 | attribute that its _tags_ metadata wasnt defined or defined as _['default']_ can be updated. 122 | 123 | With this specific example, since _password_ is tagged with _private_, you can update by suppling the _private_ tag 124 | to the `update()` 2nd parameter as: 125 | 126 | ``` javascript 127 | u1.update(someObj, 'private') 128 | console.log(u1.name()); 129 | //prints bar 130 | console.log(u1.password()); 131 | //NOTE: prints newpassword 132 | ``` 133 | 134 | 135 | # Validators 136 | 137 | ## Presence 138 | 139 | The _Presence_ ensure that an attribute value is not null or empty string, example: 140 | 141 | ```javascript 142 | var User = model("User").attr('name', { 143 | validations: { 144 | presence: true 145 | }); 146 | ``` 147 | 148 | ### Options 149 | 150 | * `true` - value will be required, default message is set. 151 | * `message` - string represents the error message if validator fails. 152 | 153 | Example with custom message: 154 | 155 | ```javascript 156 | validations: { 157 | presence: { 158 | message: 'Name is required!' 159 | } 160 | } 161 | ``` 162 | 163 | ## Length 164 | 165 | Validates rules of the length of a property value. 166 | 167 | ### Options 168 | 169 | * `is` keyword or `number` - An exact length 170 | * `array` - Will expand to `minimum` and `maximum`. First element is the lower bound, second element is the upper bound. 171 | * `allowBlank` - Validation is skipped if equal to `true` and value is empty 172 | * `minimum` - Minimum length of the value allowed 173 | * `maximum` - Maximum length of the value allowed 174 | 175 | ### Messages 176 | * `wrongLength` - any string represents the error message if `is`/`number` validation fails. 177 | * `tooShort` - any string represents the error message if `minimum` validation fails. 178 | * `tooLong` - any string represents the error message if `maximum` validation fails. 179 | 180 | ```javascript 181 | // Examples of is, both are equal, exact 3 length match 182 | length: 3 183 | length: {is: 3} 184 | //same as above, but empty string is allowed 185 | length: { is: 3, allowBlank: true } 186 | //min legnth: 2, max length: 4 187 | length: [2, 4] 188 | //same as above with custom error messages 189 | length: { minimum: 2, maximum: 4, messages { tooShort: 'min 3 length!', tooLong: 'max 5 length!' } } 190 | ``` 191 | 192 | ## Format 193 | 194 | Regexp test validator 195 | 196 | ### Options 197 | 198 | * `with` - the regular expression to test 199 | * `allowBlank` - Validation is skipped if equal to `true` and value is empty 200 | * `message` - any string represents the error message. 201 | 202 | ```javascript 203 | // Examples 204 | format: { with: /^\d*$/, allowBlank: true, message: 'only digits are allowed, or empty string.' } 205 | ``` 206 | 207 | # Tags 208 | 209 | nodejs-model supports tags per defined attribute, when new attribute is defined with no _tags_ it will be automatically 210 | tagged with the _default_ tag. 211 | 212 | Methods such as toJSON(tags_array) or `update(updatedObj, tags_array)` are accessbility aware when 213 | updating or producing model instance output. 214 | 215 | 216 | You can define tags per attribute by: 217 | 218 | ``` javascript 219 | User = model("User").attr('name', { 220 | tags: ['ui', 'registered'] 221 | }).attr('password', { 222 | tags: ['private'] 223 | }).attr('age'); 224 | 225 | u1 = User.create(); 226 | u1.name('foo'); 227 | u1.password('secret'); 228 | u1.age(55); 229 | 230 | console.log(u1.toJSON()); 231 | //prints { age: 55 }, this is because invoking toJSON(), it will only create an object with attributes defined 232 | as public. 233 | 234 | console.log(u1.toJSON(['ui', 'private'])); 235 | //prints { name: 'foo', password: 'secret' } 236 | 237 | //* means any property with any tags 238 | console.log(u1.toJSON('*')); 239 | //prints { name: 'foo', password: 'secret', age: 55 } 240 | ``` 241 | 242 | Update mehtod `someInstance.update(newObj, tags)` is also _tags-aware_ as with `someInstance.toJSON(tags)`. 243 | 244 | 245 | #Initializing Model Instances 246 | 247 | It is possible to initialize a model instance by suppliying an `init` method on the Model level, 248 | 249 | Here is an example how to initialize a creation date attribute for a model: 250 | 251 | ```javascript 252 | var P = model('Person').attr('name').attr('creation_date'); 253 | 254 | //will be invoked just after a model is instantiated by P.create() 255 | P.init = function(instance) { 256 | instance.creationDate(d); 257 | }; 258 | 259 | p1 = P.create(); 260 | 261 | console.log(p1.creationDate()) 262 | //prints a date 263 | ``` 264 | 265 | #More Info 266 | Check wiki pages: 267 | 268 | * [Custom Validator per Model](https://github.com/asaf/nodejs-model/wiki/Custom-Validator-per-Model) 269 | * [Conditional Validator](https://github.com/asaf/nodejs-model/wiki/Conditional-Validator) 270 | 271 | 272 | #Contributers 273 | 274 | * [amitpaz](https://github.com/amitpaz) - Co author, design, tests, etc. 275 | 276 | #Contributions 277 | 278 | You can contribute in few ways: 279 | 280 | * Just use the module, this is the open source way, right? more usages, more stable and robust the model will be. 281 | * Star it! :) - if you'r happy with it and find it useful. 282 | * Code, if you are a coder and would like to contribute code then visit the Development page. 283 | 284 | #License 285 | 286 | See _LICENSE_ file. 287 | -------------------------------------------------------------------------------- /lib/attrs_defs.coffee: -------------------------------------------------------------------------------- 1 | s = require 'stampit' 2 | _s = require 'underscore.string' 3 | 4 | #Attributes definitions closure 5 | attrsDefs = s().enclose(() -> 6 | #a hash of attribute definitions in the notion of attrsDefsHash[attr_name] = meta 7 | attrsDefsHash = {} 8 | #the attribute name of the primary key 9 | primaryKey = null 10 | #an object contains functions accessors 11 | accessors = {} 12 | 13 | ### 14 | Define a new attribute 15 | 16 | @param {String} name attribute name 17 | @param {Object} meta metadata of the defined attribute including validations rules, sanitization, tags, etc. 18 | @return {Function} self 19 | @api public 20 | ### 21 | @attr = (name, meta) -> 22 | attrsDefsHash[name] = meta ?= {} 23 | if name is '_id' or name is 'id' 24 | attrsDefsHash[name].primaryKey = true 25 | primaryKey = name 26 | 27 | #handle tags 28 | if not meta.tags? 29 | meta.tags = ['default'] 30 | 31 | accessorName = _s.camelize(name) 32 | accessors[accessorName] = (value) -> 33 | #if 0 args its a getter 34 | if arguments.length is 0 35 | @attrs[name] 36 | else 37 | #otherwise its a setter 38 | if value is null 39 | @dirty[name] = value 40 | delete @attrs[name] 41 | else 42 | @dirty[name] = value 43 | @attrs[name] = value 44 | @ 45 | 46 | @ 47 | 48 | @set = (name, meta) -> 49 | attrsDefsHash[prop] = value 50 | @ 51 | 52 | @get = (prop) -> 53 | attrsDefsHash[prop] 54 | 55 | @attrsDefs = () -> 56 | if arguments.length is 0 57 | return attrsDefsHash 58 | else 59 | return 'NOT SUPPORTED' 60 | 61 | @getAccessors = () -> 62 | return accessors 63 | 64 | @ 65 | ) 66 | 67 | module.exports = attrsDefs -------------------------------------------------------------------------------- /lib/index.coffee: -------------------------------------------------------------------------------- 1 | ### 2 | # Model Module 3 | # 4 | ### 5 | model = require './model' 6 | u = require './utils' 7 | s = require 'stampit' 8 | emitter = require('events').EventEmitter 9 | Validators = require './validators' 10 | 11 | ### 12 | Creates a new model (defnition) with the given type. 13 | 14 | @param {String} type of the model 15 | @return {Object} an instantiated model definition 16 | ### 17 | create = (type) -> 18 | if u.isBlank type 19 | throw {code: 500, message: "Model type is required."} 20 | 21 | mF = model.methods(emitter.prototype) 22 | m = mF.create() 23 | 24 | m.setType type 25 | m.validators Validators 26 | m 27 | 28 | #expose the create factory 29 | module.exports = create -------------------------------------------------------------------------------- /lib/messages.coffee: -------------------------------------------------------------------------------- 1 | exports.messages = 2 | blank: "can't be blank", 3 | tooShort: "length is too short" 4 | tooLong: "length is too long" 5 | wrongLength: "length is incorrect" 6 | invalid: "input is invalid" 7 | -------------------------------------------------------------------------------- /lib/model.coffee: -------------------------------------------------------------------------------- 1 | attrsDefs = require './attrs_defs' 2 | u = require './utils' 3 | model_instance = require './model_instance' 4 | s = require 'stampit' 5 | emitter = require('events').EventEmitter 6 | 7 | #Model closure 8 | model = s().enclose(() -> 9 | type = undefined #a string represents the model type 10 | validators = {} 11 | 12 | @getType = () -> 13 | type 14 | 15 | @setType = (model_type) -> 16 | type = model_type 17 | 18 | @init = () -> 19 | @ 20 | 21 | @validators = (default_validators) -> 22 | if arguments.length is 0 23 | validators 24 | else 25 | validators = default_validators 26 | 27 | @validator = (name, fn) -> 28 | validators[name] = fn 29 | 30 | #Create a new model instance from this model definition 31 | @create = (fromObject, tags) -> 32 | eventsPrototype = emitter.prototype 33 | objF = s().methods(@getAccessors(), eventsPrototype).state( 34 | attrs: {} 35 | dirty: {} 36 | errors: [] 37 | isValid: false 38 | ) 39 | 40 | staticF = s(model_instance({model: @})) 41 | objFactory = s.compose(objF, staticF) 42 | modelInstance = objFactory.create() 43 | @init(modelInstance) 44 | 45 | if fromObject 46 | #no tags mean any 47 | if not tags? 48 | tags = '*' 49 | 50 | modelInstance.update(fromObject, tags) 51 | 52 | 53 | @emit('model:created', modelInstance) 54 | 55 | modelInstance 56 | 57 | @ 58 | ) 59 | 60 | module.exports = s.compose model, attrsDefs -------------------------------------------------------------------------------- /lib/model_instance.coffee: -------------------------------------------------------------------------------- 1 | Q = require 'q' 2 | s = require 'stampit' 3 | _ = require 'underscore' 4 | _s = require 'underscore.string' 5 | u = require './utils' 6 | 7 | model_instance = s().enclose(() -> 8 | model = @model 9 | delete @model 10 | isNew = true 11 | 12 | @isNew = () -> 13 | isNew 14 | 15 | @setNew = (val) -> 16 | if val then isNew = true else isNew = false 17 | 18 | @validate = (filter) -> 19 | canValidate = (options, validator) => 20 | #if options is an object then seek the 'if' fn as the object's property 21 | if typeof (options) is "object" 22 | if options["if"] 23 | #options[if] is a function, execute it. 24 | if typeof (options.if) is "function" 25 | options.if @, validator 26 | #options[if] is a string 27 | else if typeof (options.if) is "string" 28 | #is the current model instance has a direct method that corresponds to the options[if] value? 29 | if typeof (@[options.if]) is "function" 30 | @[options.if]() 31 | #otherwise try as a property 32 | else if typeof @[options]["if"]() is "function" 33 | @[options].if() 34 | #We cant find how to handle the if criteria, then for safety validator should be executed 35 | else 36 | true 37 | #Same logic but '!' should be for unless as 'if' above 38 | else if options.unless 39 | if typeof (options.unless) is "function" 40 | not options.unless @, validator 41 | else if typeof (options.unless) is "string" 42 | if typeof (@[options.unless]) is "function" 43 | not @[options.unless]() 44 | else if typeof @[options]["unless"]() is "function" 45 | not @[options].unless() 46 | #there is no if/unless properties in the validator options hash then validator should be executed 47 | else 48 | true 49 | #in case options is not an object the validator should be executed 50 | else 51 | true 52 | 53 | Validators = model.validators() 54 | 55 | @errors = {} 56 | oper = Q.defer() 57 | deffers = [] 58 | 59 | if filter 60 | vProps = [filter]; 61 | else 62 | attrsDefs = model.attrsDefs() 63 | 64 | for prop of attrsDefs 65 | validators = attrsDefs[prop].validations 66 | if validators? 67 | for validator of validators 68 | validator_options = validators[validator] 69 | if canValidate validator_options, validators[validator] 70 | if Validators[validator]? and typeof Validators[validator] is 'function' 71 | accessor = _s.camelize prop 72 | deffers = deffers.concat Validators[validator](@, accessor, validator_options) 73 | 74 | Q.allSettled(deffers).then((result) => 75 | @isValid = Object.keys(@errors).length is 0 76 | oper.resolve() 77 | ) 78 | oper.promise 79 | 80 | @getType = () -> 81 | model.getType() 82 | 83 | @addError = (attr, message) -> 84 | @errors[attr] = (@errors[attr] || []).concat(message) 85 | 86 | @update = (object, tags) -> 87 | attrsDefs = model.attrsDefs() 88 | 89 | for attrName of object 90 | if not attrsDefs[attrName] 91 | continue 92 | 93 | if u.isAttributeMatchesTags model, attrName, tags 94 | @attrs[attrName] = object[attrName] 95 | 96 | @ 97 | 98 | 99 | @toJSON = (tags) -> 100 | attrsToReturn = {} 101 | 102 | for attrName of @attrs 103 | if u.isAttributeMatchesTags model, attrName, tags 104 | attrsToReturn[attrName] = @attrs[attrName] 105 | 106 | attrsToReturn 107 | @ 108 | ) 109 | 110 | module.exports = model_instance -------------------------------------------------------------------------------- /lib/utils.coffee: -------------------------------------------------------------------------------- 1 | _ = require 'underscore' 2 | 3 | exports.isBlank = (val) -> 4 | return val isnt 0 && (!val || /^\s*$/.test(''+val)) 5 | 6 | exports.grep = (elems, callback, inv) -> 7 | retVal = undefined 8 | ret = [] 9 | i = 0 10 | length = elems.length 11 | inv = !!inv 12 | 13 | # Go through the array, only saving the items 14 | # that pass the validator function 15 | while i < length 16 | retVal = !!callback(elems[i], i) 17 | ret.push elems[i] if inv isnt retVal 18 | i++ 19 | ret 20 | 21 | exports.getTags = (tags) -> 22 | negTags = (inv=false) -> 23 | exports.grep(tags, (ele) -> 24 | ele.indexOf('!') is 0 25 | , inv) 26 | 27 | if exports.isBlank tags 28 | {pos: ['default'], neg: []} 29 | else if tags.constructor isnt Array 30 | if tags.indexOf('!') is 0 31 | {neg: [tags.slice(1,tags.length)], pos: []} 32 | else 33 | {pos: [tags], neg: []} 34 | else 35 | #TODO: else ensure each tag is a string 36 | neg = negTags() 37 | pos = negTags(true) 38 | 39 | for k,v of neg 40 | neg[k] = v.slice(1, v.length) 41 | 42 | if _.intersection(pos, neg).length > 0 43 | throw 'Intersection is not allowed.' 44 | else 45 | {pos: pos, neg: neg} 46 | 47 | exports.isAttributeMatchesTags = (model, attrName, tags) -> 48 | attrTags = exports.getTags(model.attrsDefs()[attrName].tags).pos 49 | tagsReq = exports.getTags(tags) 50 | 51 | #console.log 'ATTR TAGS: ', attrTags 52 | #console.log 'REQ TAGS: ', tagsReq 53 | 54 | #In case we only recieve negative tags, we assume it's been read as: 'Gimme everything BUT !negative !tags' 55 | if tagsReq.neg.length > 0 and tagsReq.pos.length is 0 56 | tagsReq.pos.push('*') 57 | 58 | ack = false 59 | 60 | if _.contains(tagsReq.pos, '*') or _.intersection(tagsReq.pos, attrTags).length > 0 61 | ack = true 62 | 63 | if ack 64 | if _.intersection(tagsReq.neg, attrTags).length > 0 65 | ack = false 66 | 67 | ack -------------------------------------------------------------------------------- /lib/validators.coffee: -------------------------------------------------------------------------------- 1 | require("fs").readdirSync(__dirname + "/validators").forEach (file) -> 2 | if file.match(/.+\.coffee/g) isnt null 3 | name = file.replace(".coffee", "") 4 | exports[name] = require("./validators/" + file)[name] 5 | -------------------------------------------------------------------------------- /lib/validators/format.coffee: -------------------------------------------------------------------------------- 1 | Q = require 'q' 2 | v = require 'validator' 3 | m = require '../messages' 4 | u = require '../utils' 5 | 6 | exports.format = (model, property, options) -> 7 | d = Q.defer() 8 | if options.constructor is RegExp 9 | options = 10 | "with": options 11 | 12 | if !options.message? 13 | options.message = m.messages.invalid 14 | 15 | #Ensure regexp is valid 16 | regexpTest = options['with'].test 17 | if regexpTest is undefined 18 | throw {code: 500, message: "The specified regexp #{options['with']} is invalid.", status: "failure"} 19 | 20 | if u.isBlank model[property]() 21 | if not options.allowBlank 22 | model.addError property, options.message 23 | else if options['with'] && not options['with'].test model[property]() 24 | model.addError property, options.message 25 | else if options.without && options.without.test model[property]() 26 | model.addError property, options.message 27 | 28 | d.resolve() 29 | 30 | d.promise -------------------------------------------------------------------------------- /lib/validators/length.coffee: -------------------------------------------------------------------------------- 1 | Q = require 'q' 2 | v = require 'validator' 3 | m = require '../messages' 4 | u = require '../utils' 5 | 6 | exports.length = (model, property, options) -> 7 | d = Q.defer() 8 | 9 | #options may contain the following types 10 | TYPES = 11 | 'is' : '==' #exact expected length 12 | 'minimum' : '>=' #minumum length allowed 13 | 'maximum' : '<=' #maximum length allowed 14 | 15 | #message key per type 16 | MESSAGES = 17 | 'is' : 'wrongLength', #The error message key when 'is' used. 18 | 'minimum' : 'tooShort', #The error message key when minimum is used. 19 | 'maximum' : 'tooLong' #The error message kwy when maximum is used. 20 | 21 | keys = Object.keys(MESSAGES) 22 | 23 | if options.messages is undefined 24 | options.messages = {} 25 | 26 | #If options is 'length: x' then define 'is= x' 27 | if typeof(options) is 'number' 28 | options = 29 | 'is': options 30 | 31 | 32 | #options may be {is: x} or {minimum: x, maximum y}, it may also be defined with messages object such as: 33 | ##{minimum: x, maximum y, messages {tooShort: 'value must be at least X chars length} 34 | #in case options contains a TYPE but corresponding message doesnt exist, then get the default message for the 35 | #corresponding type. 36 | index = 0 37 | while index < keys.length 38 | key = keys[index] 39 | if options[key] isnt `undefined` and options.messages[MESSAGES[key]] is `undefined` 40 | options.messages[MESSAGES[key]] = m.messages[MESSAGES[key]] 41 | index++ 42 | 43 | #default tokenizier is none, but may recieve one externally 44 | tokenizer = options.tokenizer or 'split("")' 45 | tokenizedLength = new Function("value", "return value." + tokenizer + ".length")(model[property]() or "") 46 | 47 | allowBlankOptions = {} 48 | if options.is 49 | allowBlankOptions.message = options.messages.wrongLength 50 | else allowBlankOptions.message = options.messages.tooShort if options.minimum 51 | 52 | if u.isBlank(model[property]()) 53 | model.addError property, allowBlankOptions.message if not options.allowBlank and (options.is or options.minimum) 54 | else 55 | for check of TYPES 56 | oper = TYPES[check] 57 | continue unless options[check] 58 | fn = new Function("return " + tokenizedLength + " " + oper + " " + options[check]) 59 | model.addError property, options.messages[MESSAGES[check]] unless fn() 60 | 61 | d.resolve() 62 | d.promise -------------------------------------------------------------------------------- /lib/validators/presence.coffee: -------------------------------------------------------------------------------- 1 | Q = require 'q' 2 | v = require 'validator' 3 | m = require '../messages' 4 | 5 | exports.presence = (model_instance, property, options) -> 6 | d = Q.defer() 7 | 8 | options = {} if options is true 9 | 10 | if !options.message? 11 | options.message = m.messages.blank 12 | 13 | try 14 | v.check(model_instance[property]()).notNull() 15 | catch e 16 | model_instance.addError(property, options.message) 17 | 18 | d.resolve() 19 | d.promise -------------------------------------------------------------------------------- /module.js: -------------------------------------------------------------------------------- 1 | try { 2 | module.exports = require('./compiled'); 3 | } catch(error) { 4 | require('./node_modules/coffee-script'); 5 | module.exports = require('./lib'); 6 | } 7 | 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-model", 3 | "description": "A simple, minimalistic object model for nodejs", 4 | "version": "0.1.6", 5 | "keywords": [ 6 | "model", 7 | "schema", 8 | "validations" 9 | ], 10 | "author": { 11 | "name": "Asaf Shakarchi", 12 | "email": "asaf000@gmail.com" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git://github.com/asaf/nodejs-model" 17 | }, 18 | "bugs": { 19 | "url": "https://github.com/asaf/nodejs-model/issues" 20 | }, 21 | "scripts": { 22 | "test": "./node_modules/mocha/bin/mocha test/test.coffee", 23 | "compile": "rm -rf ./compiled/* ; ./node_modules/coffee-script/bin/coffee -o compiled/ -c lib/" 24 | }, 25 | "main": "module.js", 26 | "dependencies": { 27 | "validator": "~1.4.0", 28 | "coffee-script": "1.4.0", 29 | "q": "~0.9.6", 30 | "underscore": "~1.5.1", 31 | "stampit": "~0.5.1", 32 | "chai-extras": "~1.1.0", 33 | "underscore.string": "~2.3.3" 34 | }, 35 | "devDependencies": { 36 | "mocha": "*", 37 | "chai": "*" 38 | }, 39 | "optionalDependencies": {}, 40 | "engines": { 41 | "node": "*" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /test/mocha.opts: -------------------------------------------------------------------------------- 1 | --compilers coffee:coffee-script 2 | --reporter spec 3 | --timeout 5000 4 | -------------------------------------------------------------------------------- /test/test-attributes-tags.coffee: -------------------------------------------------------------------------------- 1 | u = require 'util' 2 | model = require '../lib/index' 3 | _ = require 'underscore' 4 | 5 | describe 'Attributes Tags', -> 6 | it "Ensure default tag is 'default'", (done) -> 7 | P = model("Person").attr('name').attr('age') 8 | P.attrsDefs().name.tags.should.deep.equal ['default'] 9 | P.attrsDefs().age.tags.should.deep.equal ['default'] 10 | 11 | p1 = P.create() 12 | p1.name('foo') 13 | p1.age(1) 14 | 15 | p1Obj = 16 | name: 'foo' 17 | age: 1 18 | 19 | p1.toJSON().should.deep.equal p1Obj 20 | p1.toJSON('default').should.deep.equal p1Obj 21 | p1.toJSON('priv').should.deep.equal {} 22 | 23 | done() 24 | 25 | #TODO: More tests goes here -------------------------------------------------------------------------------- /test/test-basic_model.coffee: -------------------------------------------------------------------------------- 1 | u = require 'util' 2 | model = require '../lib/index' 3 | 4 | describe 'Model creations', -> 5 | it 'model should be a factory function', (done) -> 6 | if typeof(model) is 'function' 7 | done() 8 | 9 | it 'Create a basic model', (done) -> 10 | foo = model("Foo") 11 | foo.getType().should.equal 'Foo' 12 | foo.attrsDefs().should.deep.equal {} 13 | done() 14 | 15 | it 'model should be created with simple attributes, chained', (done) -> 16 | foo = model("Foo") 17 | .attr('id') 18 | .attr('content') 19 | 20 | foo.attrsDefs().should.have.property('id') 21 | foo.attrsDefs().should.have.property('content') 22 | 23 | done() 24 | 25 | it 'Model should be created with meta attributes, chained', (done) -> 26 | meta = 27 | validations: 28 | presence: 29 | message: 'required!' 30 | converters: 31 | to_capital: true 32 | foo = model("Foo") 33 | .attr('id', meta 34 | ) 35 | .attr('content') 36 | 37 | foo.attrsDefs().id.should.deep.equal meta 38 | done() 39 | 40 | it 'Instantiating a model instance', (done) -> 41 | P = model("Person") 42 | .attr('id') 43 | .attr('name') 44 | 45 | p = P.create() 46 | if p.id() isnt undefined 47 | throw 'p.id() Should be undefined!' 48 | p.id('1').name('foo') 49 | #By default models instances are indicated as new 50 | p.isNew().should.equal true 51 | 52 | p.id().should.equal '1' 53 | p.name().should.equal 'foo' 54 | 55 | done() 56 | 57 | it 'Setting an attribute to null should delete the attribute from the model instance', (done) -> 58 | P = model("Person").attr('name') 59 | 60 | p1 = P.create() 61 | p1.name('foo') 62 | p1.attrs.should.contain.property('name', 'foo') 63 | p1.name(null) 64 | p1.attrs.should.not.contain.property('name') 65 | done() 66 | 67 | 68 | it 'Accessors for var_with_underscore should be camelized', (done) -> 69 | P = model('Person').attr('creation_date') 70 | p = P.create() 71 | p.should.not.have.method('creation_date') 72 | p.should.have.method('creationDate') 73 | 74 | p.creationDate('foo') 75 | p.creationDate().should.equal 'foo' 76 | 77 | done() 78 | 79 | it 'Initializing model via the init() method', (done) -> 80 | P = model('Person').attr('name').attr('creation_date') 81 | d = new Date() 82 | P.init = (instance) -> 83 | instance.creationDate(d) 84 | 85 | p1 = P.create() 86 | p1.creationDate().should.equal d 87 | done() 88 | 89 | it 'Creating a model instance should produce a create event', (done) -> 90 | P = model('Person') 91 | .attr('id') 92 | 93 | P.on('model:created', (p) -> 94 | p.getType().should.equal 'Person' 95 | done() 96 | ) 97 | 98 | Post = model('Post') 99 | 100 | Post.on('model:created', () -> 101 | done() 102 | ) 103 | 104 | P.create() 105 | 106 | it 'Create a model instance by supplying existing object', (done) -> 107 | Per = model("Person").attr("id").attr("name") 108 | 109 | perObj = 110 | id: '1' 111 | name: 'foo' 112 | 113 | p1 = Per.create(perObj) 114 | p1.id().should.equal '1' 115 | p1.name().should.equal 'foo' 116 | 117 | done() 118 | 119 | it 'Creating multiple model defs / instances should have different scopes', (done) -> 120 | Per = model("Person").attr("id").attr("name") 121 | Post = model("Post").attr("id").attr("body").attr("created_at") 122 | 123 | Object.keys(Per.attrsDefs()).length.should.equal 2 124 | Per.attrsDefs().should.have.property('id') 125 | Per.attrsDefs().should.have.property('name') 126 | Object.keys(Post.attrsDefs()).length.should.equal 3 127 | Post.attrsDefs().should.have.property('id') 128 | Post.attrsDefs().should.have.property('body') 129 | Post.attrsDefs().should.have.property('created_at') 130 | 131 | p1 = Per.create() 132 | p1.id('1') 133 | p1.name('foo') 134 | 135 | p2 = Per.create() 136 | p2.id('2') 137 | p2.name('bar') 138 | 139 | p1.id().should.equal '1' 140 | p1.name().should.equal 'foo' 141 | p2.id().should.equal '2' 142 | p2.name().should.equal 'bar' 143 | 144 | done() 145 | 146 | it 'Validate a simple model with presence validator', (done) -> 147 | P = model("Person").attr('name', 148 | validations: 149 | presence: 150 | message: 'Required!' 151 | ) 152 | 153 | p1 = P.create() 154 | p1.errors.should.have.length 0 155 | p1.isValid.should.equal false 156 | p1.validate().then((validated) -> 157 | Object.keys(p1.errors).should.have.length 1 158 | p1.errors.should.deep.equal {name: ['Required!']} 159 | p1.isValid.should.equal false 160 | 161 | true 162 | ).then(() -> 163 | p1.name('foo') 164 | p1.validate().then((validated) -> 165 | Object.keys(p1.errors).should.have.length 0 166 | p1.isValid.should.equal true 167 | 168 | done() 169 | ) 170 | ) 171 | 172 | it 'Ensure validation dont fail when having attributes with _', (done) -> 173 | P = model("Person").attr('creation_date', 174 | validations: 175 | precense: 176 | message: 'Required!' 177 | ) 178 | 179 | p1 = P.create() 180 | p1.creationDate new Date() 181 | p1.validate().then(() -> 182 | Object.keys(p1.errors).should.have.length 0 183 | p1.isValid.should.equal true 184 | done() 185 | ) 186 | 187 | it 'Validate a model with combined validators', (done) -> 188 | P = model("Person").attr('name', 189 | validations: 190 | presence: 191 | message: 'Required!' 192 | ).attr('title' 193 | validations: 194 | length: 195 | messages: 196 | tooShort: 'too short!' 197 | tooLong: 'too long!' 198 | minimum: 5 199 | maximum: 10 200 | allowBlank: false 201 | ) 202 | 203 | p1 = P.create() 204 | p1.validate().then(() -> 205 | Object.keys(p1.errors).should.have.length 2 206 | p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too short!' ] } 207 | p1.isValid.should.equal false 208 | 209 | true 210 | ).then(() -> 211 | p1.title('hello') 212 | p1.validate().then(() -> 213 | p1.errors.should.deep.equal {name: ['Required!' ]} 214 | 215 | true 216 | ) 217 | ).then(() -> 218 | p1.title('hello-world') 219 | p1.validate().then(() -> 220 | p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too long!' ] } 221 | p1.isValid.should.equal false 222 | 223 | true 224 | ) 225 | ).then(() -> 226 | p1.name('foo') 227 | p1.title('hello') 228 | p1.validate().then(() -> 229 | Object.keys(p1.errors).should.have.length 0 230 | p1.isValid.should.equal true 231 | done() 232 | ) 233 | ) 234 | 235 | it 'Test TOJSON', (done) -> 236 | P = model("User").attr("password", 237 | tags: ['private'] 238 | ).attr("name") 239 | 240 | p1 = P.create() 241 | p1.name('foo') 242 | p1.password('secret') 243 | p1.toJSON().should.deep.equal {name: 'foo'} 244 | p1.toJSON('private').should.deep.equal {password: 'secret'} 245 | p1.toJSON('*').should.deep.equal {password: 'secret', name: 'foo'} 246 | p1.toJSON('!private').should.deep.equal {name: 'foo'} 247 | p1.toJSON('none').should.deep.equal {} 248 | 249 | done() 250 | 251 | it 'Update model instance via update()', (done) -> 252 | P = model("Person").attr('name').attr('age') 253 | .attr('password', 254 | tags: ['private'] 255 | ) 256 | 257 | p1 = P.create() 258 | p1.name('foo') 259 | p1.age(10) 260 | p1.password('secret') 261 | 262 | p1.update( 263 | name: 'bar' 264 | age: 20 265 | password: 'ignore!' 266 | ) 267 | 268 | p1.name().should.equal 'bar' 269 | p1.age().should.equal 20 270 | p1.password().should.equal 'secret' 271 | 272 | done() 273 | 274 | it 'Ensure undefined attributes are not causing errors nor updating the model', (done) -> 275 | P = model("Person").attr('name') 276 | p1 = P.create() 277 | p1.name 'foo' 278 | 279 | newObj = 280 | name: 'bar' 281 | other: 'baz' 282 | 283 | p1.update(newObj, '*') 284 | p1.name().should.equal 'bar' 285 | if p1.other isnt undefined 286 | throw 'Expected p1.other to be undefined!' 287 | p1.attrs.should.not.have.property('other') 288 | 289 | done() 290 | 291 | it 'Ensure set model.isNew to false works', (done) -> 292 | P = model("Person").attr('name') 293 | p1 = P.create() 294 | 295 | p1.isNew().should.equal true 296 | p1.setNew(false) 297 | p1.isNew().should.equal false 298 | 299 | done() 300 | ### -------------------------------------------------------------------------------- /test/test-conditional_validators.coffee: -------------------------------------------------------------------------------- 1 | u = require 'util' 2 | model = require '../lib/index' 3 | 4 | describe 'Conditional Validators', -> 5 | it 'Ensure conditional Validator represented as an inline IF function is executed.', (done) -> 6 | p1 = null 7 | P = model("Person").attr('id').attr('name', 8 | validations: 9 | presence: 10 | message: 'required!' 11 | if: (model, validator) -> 12 | model.should.deep.equal p1 13 | if typeof(validator.constructor) is 'function' 14 | done() 15 | ) 16 | 17 | p1 = P.create() 18 | p1.id '1234-4321' 19 | p1.validate() 20 | 21 | it 'Ensure conditional validator represented as an inline IF function works as expected.', (done) -> 22 | P = model("Person").attr('name', 23 | validations: 24 | length: 25 | is: 9 26 | message: '9 length exepcted!' 27 | if: (model, validator) -> 28 | if model.name() is 'foo' 29 | true 30 | else 31 | false 32 | ) 33 | 34 | p1 = P.create() 35 | p1.name 'foo' 36 | 37 | p1.validate().then(() -> 38 | p1.isValid.should.equal false 39 | 40 | p1.name 'other' 41 | p1.validate().then(() -> 42 | p1.isValid.should.equal true 43 | done() 44 | ) 45 | ) 46 | 47 | #TODO: 48 | #it 'Ensure conditional Validator represented as an IF function in the model works as expected.', (done) -> 49 | #TODO: 50 | #it 'Ensure conditional Validator represented as an IF property in the model works as expected.', (done) -> 51 | #TODO: 52 | #it 'Ensure validator is executed in case IF property is malformed (not an inline fn, nor model.func or model property value as fn)' 53 | 54 | 55 | it 'Ensure conditional validator represented as inline UNLESS function is executed', (done) -> 56 | p1 = null 57 | P = model("Person").attr('id').attr('name', 58 | validations: 59 | presence: 60 | message: 'required!' 61 | unless: (model, validator) -> 62 | model.should.deep.equal p1 63 | if typeof(validator.constructor) is 'function' 64 | done() 65 | ) 66 | 67 | p1 = P.create() 68 | p1.id '1234-4321' 69 | p1.validate() 70 | 71 | it 'Ensure conditional validator represented as an inline UNLESS function works as expected.', (done) -> 72 | P = model("Person").attr('name', 73 | validations: 74 | length: 75 | is: 9 76 | message: '9 length exepcted!' 77 | unless: (model, validator) -> 78 | if model.name() is 'foo' 79 | false 80 | else 81 | true 82 | ) 83 | 84 | p1 = P.create() 85 | p1.name 'foo' 86 | 87 | p1.validate().then(() -> 88 | p1.isValid.should.equal false 89 | 90 | p1.name 'other' 91 | p1.validate().then(() -> 92 | p1.isValid.should.equal true 93 | done() 94 | ) 95 | ) 96 | 97 | #TODO: 98 | #it 'Ensure conditional Validator represented as an UNLESS function in the model works as expected.', (done) -> 99 | #TODO: 100 | #it 'Ensure conditional Validator represented as an UNLESS property in the model works as expected.', (done) -> 101 | #TODO: 102 | #it 'Ensure validator is executed in case UNLESS property is malformed (not an inline fn, nor model.func or model property value as fn)' 103 | -------------------------------------------------------------------------------- /test/test-custom_validators.coffee: -------------------------------------------------------------------------------- 1 | u = require 'util' 2 | model = require '../lib/index' 3 | 4 | describe 'Custom Validators', -> 5 | it 'Test custom validator per Model', (done) -> 6 | P = model("Person").attr('id') 7 | .attr('name', 8 | validations: 9 | presence: true 10 | uniqueUserName: 11 | message: 'Name already exist.' 12 | ) 13 | 14 | P.validator('uniqueUserName', (model, property, options) -> 15 | model.name().should.equal 'foo' 16 | property.should.equal 'name' 17 | options.should.deep.equal { message: 'Name already exist.' } 18 | 19 | if model[property]() is 'foo' 20 | model.addError property, options.message 21 | ) 22 | 23 | p1 = P.create() 24 | p1.name 'foo' 25 | p1.validate().then(() -> 26 | p1.isValid.should.equal false 27 | p1.errors.should.deep.equal { name: [ 'Name already exist.' ] } 28 | done() 29 | ) -------------------------------------------------------------------------------- /test/test-utils.coffee: -------------------------------------------------------------------------------- 1 | u = require '../lib/utils' 2 | model = require '../lib/index' 3 | 4 | describe 'Test Utils', -> 5 | it 'Test isBlank()', (done) -> 6 | u.isBlank('foo').should.equal false 7 | u.isBlank('').should.equal true 8 | u.isBlank().should.equal true 9 | u.isBlank(null).should.equal true 10 | u.isBlank(undefined).should.equal true 11 | 12 | done() 13 | 14 | it 'Test getTags()', (done) -> 15 | u.getTags().pos.should.deep.equal ['default'] 16 | u.getTags().neg.should.have.length 0 17 | u.getTags('foo').pos.should.deep.equal ['foo'] 18 | u.getTags('foo').neg.should.have.length 0 19 | u.getTags('!foo').pos.should.have.length 0 20 | u.getTags('!foo').neg.should.deep.equal ['foo'] 21 | u.getTags(['foo']).pos.should.deep.equal ['foo'] 22 | u.getTags(['!foo']).neg.should.deep.equal ['foo'] 23 | u.getTags(['foo', 'bar']).pos.should.deep.equal ['foo', 'bar'] 24 | u.getTags(['!foo', '!bar']).neg.should.deep.equal ['foo', 'bar'] 25 | tags = u.getTags(['!foo', 'baz', '!bar', 'qux']) 26 | tags.neg.should.deep.equal ['foo', 'bar'] 27 | tags.pos.should.deep.equal ['baz', 'qux'] 28 | 29 | done() 30 | 31 | it 'Confict in tags should cause exception', (done) -> 32 | try 33 | u.getTags(['foo','bar','!foo']) 34 | catch e 35 | done() 36 | 37 | it 'Test isAttributeMatchesTags()', (done) -> 38 | #--two tag-- 39 | P = model("Person").attr("name", {tags: ['foo', 'bar']}) 40 | #match attribute if it has 'foo'/'bar' tag. 41 | u.isAttributeMatchesTags(P, 'name', 'foo').should.equal true 42 | u.isAttributeMatchesTags(P, 'name', 'bar').should.equal true 43 | u.isAttributeMatchesTags(P, 'name', ['foo', 'bar']).should.equal true 44 | u.isAttributeMatchesTags(P, 'name', ['foo', 'baz', 'qux']).should.equal true 45 | #match attribute if it has 'fo' tag. 46 | u.isAttributeMatchesTags(P, 'name', 'fo').should.equal false 47 | #match attribute if it has 'bar'/'baz' but doesnt have the 'foo' tag. 48 | u.isAttributeMatchesTags(P, 'name', ['baz', 'bar', '!foo']).should.equal false 49 | #match attr if it doesnt have the 'blabla/a' tags 50 | u.isAttributeMatchesTags(P, 'name', '!blabla').should.equal true 51 | u.isAttributeMatchesTags(P, 'name', '!a').should.equal true 52 | u.isAttributeMatchesTags(P, 'name', ['!a','!blabla']).should.equal true 53 | 54 | done() -------------------------------------------------------------------------------- /test/test.coffee: -------------------------------------------------------------------------------- 1 | chai = require 'chai' 2 | extras = require('chai-extras'); 3 | chai.use extras 4 | chai.should() 5 | require './validators/test-presence' 6 | require './validators/test-length' 7 | require './validators/test-format' 8 | require './test-basic_model' 9 | require './test-custom_validators' 10 | require './test-conditional_validators' 11 | require './test-attributes-tags' 12 | require './test-utils' -------------------------------------------------------------------------------- /test/validators/test-format.coffee: -------------------------------------------------------------------------------- 1 | v = require '../../lib/validators/format' 2 | model = require '../../lib/index' 3 | 4 | m = null 5 | describe 'Format validator tests', -> 6 | beforeEach (done) -> 7 | M = model("M").attr('name').attr('age') 8 | m = M.create() 9 | done() 10 | 11 | it 'With regexp, value comply', (done) -> 12 | options = 13 | "with": /^\d*$/ 14 | 15 | m.age 14 16 | v.format(m, 'age', options).then((validated) -> 17 | m.errors.should.deep.equal {} 18 | done() 19 | ) 20 | 21 | it 'With regexp and message, value not comply', (done) -> 22 | options = 23 | "with": /^\d*$/ 24 | message: 'failure!' 25 | 26 | m.age 'dooo14' 27 | v.format(m, 'age', options).then((validated) -> 28 | m.errors.age.should.deep.equal ['failure!'] 29 | done() 30 | ) 31 | 32 | it 'When regexp, not allowing blanks, value is blank', (done) -> 33 | options = 34 | "with": /^\d*$/ 35 | message: 'failure!' 36 | 37 | v.format(m, 'age', options).then((validated) -> 38 | m.errors.age.should.deep.equal ['failure!'] 39 | done() 40 | ) 41 | 42 | it 'When regexp, allowing blanks, value is blank', (done) -> 43 | options = 44 | allowBlank: true 45 | "with": /^\d*$/ 46 | 47 | v.format(m, 'age', options).then((validated) -> 48 | m.errors.should.deep.equal {} 49 | done() 50 | ) -------------------------------------------------------------------------------- /test/validators/test-length.coffee: -------------------------------------------------------------------------------- 1 | v = require '../../lib/validators/length' 2 | model = require '../../lib/index' 3 | 4 | m = null 5 | describe 'Length validator tests', -> 6 | beforeEach (done) -> 7 | M = model("M").attr('name') 8 | m = M.create() 9 | 10 | done() 11 | 12 | describe 'Is tests', -> 13 | it 'When is: 4 and value length is 4', (done) -> 14 | options = 15 | messages: 16 | wrongLength: 'wrong length' 17 | is: 4 18 | 19 | m.name('foob') 20 | v.length(m, 'name', options).then(() -> 21 | m.errors.should.deep.equal {} 22 | done() 23 | ) 24 | 25 | it 'When is: 4 and value length is 5 (longer) but no message defined', (done) -> 26 | options = 27 | is: 4 28 | 29 | m.name('foobz') 30 | v.length(m, 'name', options).then(() -> 31 | m.errors.name.should.deep.equal ['length is incorrect'] 32 | done() 33 | ) 34 | 35 | it 'When is: 4 and value length is 3 (shorter) and message defined', (done) -> 36 | options = 37 | messages: 38 | wrongLength: 'wrong' 39 | is: 4 40 | 41 | m.name('foo') 42 | v.length(m, 'name', options).then(() -> 43 | m.errors.name.should.deep.equal ['wrong'] 44 | done() 45 | ) 46 | 47 | it 'When is: 3 and value is blank, (absence of allowBlank=true eq blank not allowed)', (done) -> 48 | options = 49 | messages: 50 | wrongLength: 'wrong' 51 | is: 3 52 | 53 | v.length(m, 'name', options).then(() -> 54 | m.errors.name.should.deep.equal ['wrong'] 55 | done() 56 | ) 57 | 58 | it 'When is:3 and allowBlank=true, value is blank', (done) -> 59 | options = 60 | is: 3 61 | allowBlank: true 62 | 63 | v.length(m, 'name', options).then(() -> 64 | m.errors.should.deep.equal {} 65 | done() 66 | ) 67 | 68 | it 'When minimum: 5 and size is 5', (done) -> 69 | describe 'Minimum, Maximum', -> 70 | options = 71 | minimum: 5 72 | 73 | m.name('fooba') 74 | v.length(m, 'name', options).then((success) -> 75 | m.errors.should.deep.equal {} 76 | done() 77 | ) 78 | 79 | it 'When minimum: 5 and size is 4', (done) -> 80 | describe 'Minimum, Maximum', -> 81 | options = 82 | messages: 83 | tooShort: 'wrong!' 84 | minimum: 5 85 | 86 | m.name('foob') 87 | v.length(m, 'name', options).then((success) -> 88 | m.errors.name.should.deep.equal ['wrong!'] 89 | done() 90 | ) 91 | 92 | it 'When minimum: 3, maximum: 5, value is: 6', (done) -> 93 | describe 'Minimum, Maximum', -> 94 | options = 95 | messages: 96 | tooLong: 'long!' 97 | minimum: 3 98 | maximum: 5 99 | 100 | m.name('foobar') 101 | v.length(m, 'name', options).then((success) -> 102 | m.errors.name.should.deep.equal ['long!'] 103 | done() 104 | ) 105 | -------------------------------------------------------------------------------- /test/validators/test-presence.coffee: -------------------------------------------------------------------------------- 1 | v = require '../../lib/validators/presence' 2 | model = require '../../lib/index' 3 | 4 | m = null 5 | describe 'Presence validator tests', -> 6 | beforeEach (done) -> 7 | M = model("M").attr('name') 8 | m = M.create() 9 | done() 10 | 11 | it 'Positive test where value exist', (done) -> 12 | m.name('Some Value') 13 | options = 14 | message: 'failed validation' 15 | 16 | v.presence(m, 'name', options).then(() -> 17 | m.errors.should.deep.equal {} 18 | done() 19 | ) 20 | 21 | it 'Negative test when options is true', (done) -> 22 | options = true 23 | v.presence(m, 'name', options).then(() -> 24 | m.errors.should.deep.equal {name: ['can\'t be blank']} 25 | done() 26 | ) 27 | 28 | it 'Negative test when value is empty and options is object with message property', (done) -> 29 | options = 30 | message: 'missing' 31 | 32 | v.presence(m, 'name', options).then(() -> 33 | m.errors.should.deep.equal {name: ['missing']} 34 | done() 35 | ) --------------------------------------------------------------------------------