UNPKG

9.63 kBMarkdownView Raw
1# Validate incoming objects against Swagger Models for Node.js
2[ ![Codeship Status for atlantishealthcare/swagger-model-validator](https://codeship.com/projects/a4ec3310-3b9b-0132-060c-1e7e00028aa9/status?branch=master)](https://codeship.com/projects/42728)
3[ ![npm version](https://badge.fury.io/js/swagger-model-validator.svg)](https://badge.fury.io/js/swagger-model-validator)
4
5[![NPM](https://nodei.co/npm/swagger-model-validator.png?downloads=true)](https://nodei.co/npm-dl/swagger-model-validator/)
6
7This is a validation module for [Swagger](https://github.com/swagger-api/swagger-spec) models (version 1.2 and 2.0) for Node.js.
8
9See the [swagger-node-express](https://github.com/swagger-api/swagger-node-express) sample for more details about Swagger in Node.js.
10
11## What's Swagger?
12The goal of Swaggerâ„¢ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swager removes the guesswork in calling the service.
13
14Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more.
15
16## Validating Swagger Models?
17A Swagger Model contains the definitions of the incoming (or outgoing) object properties. Validating an incoming object matches the Swagger Model Definition is a valuable check that the correct data has been provided.
18
19This package provides a module to do just that.
20
21## Swagger versions
22This project should work against both Swagger 1.2 and Swagger 2.0. Please create a pull request if you have any fixes for Swagger 2.0 support but please remember to retain support for Swagger 1.2 as well.
23
24### Validation Notes
25It will validate int32 properly but the way javascript handles int64 makes it impossible to accurately validate int64s.
26As long as the value can be parsed by parseInt in javascript it will be accepted as an int64.
27
28It currently treats float and decimal the same but this is because javascript cannot cope with a decimal (at the moment).
29As long as the value can be parsed by parseFloat in javascript it will be accepted as a float or a decimal.
30
31It validates the date and date-time correctly. It treats all dates (and date-times) as dates and tests with a parseDate
32check. If this passes then it checks 'date' format against a length of 10 (a quick check against the ISO8601 standard, a full-date must be 10 characters long).
33
34As from version 0.3 it will now validate models referenced by the $ref keyword but it will only do this if it is called
35by the swagger function validateModel or if the native validate is called with a model array passed in.
36
37As from version 1.0.0 it will now validate arrays in models. It will validate arrays of a type and arrays of a $ref.
38
39As from version 2.1.5 it will validate models using the ```allOf``` keyword.
40### Installation
41Install swagger-model-validator
42
43```
44npm install swagger-model-validator
45```
46
47Create a validator and pass your swagger client into it.
48```
49var Validator = require('swagger-model-validator');
50var validator = new Validator(swagger);
51```
52
53Now you can call validateModel on swagger to validate an incoming json object.
54
55```
56var validation = swagger.validateModel("modelName", jsonObject, _allowBlankTarget_, _disallowExtraProperties_);
57```
58
59This returns a validation results object
60
61```
62{
63 valid: true,
64 errorCount: 0
65}
66```
67or if validation fails
68```
69{
70 valid: false,
71 errorCount: 2,
72 errors: [
73 {
74 name: 'Error',
75 message: 'An error occurred'
76 },
77 {
78 name: 'Error',
79 message: 'Another error occurred'
80 }
81 ]
82}
83```
84
85You can also call the validation directly
86
87```
88var validation = validator.validate(object, swaggerModel, swaggerModels, allowBlankTarget, disallowExtraProperties);
89```
90
91will return the same validation results but requires the actual swagger model and not its name. _The swaggerModels
92parameter is required if you want models referenced by the $ref keyword to be validated as well._
93
94### Allowing blank targets to validate
95From 1.0.2 any empty objects passed in as targets will fail validation. You can bypass this by adding a `true` value to
96the method at the end.
97
98```
99var validation = swagger.validateModel("modelName", target, true);
100```
101
102This will allow an empty object `{ }` to be validated without errors. We consider a blank object to be worthless in most
103cases and so should normally fail, but there is always the chance that it might not be worthless so we've added the bypass.
104
105### Preventing extra properties
106From 1.2 an optional parameter can be passed into the validation request to control if extra properties should be disallowed.
107If this flag is true then the target object cannot contain any properties that are not defined on the model.
108If it is blank or false then the target object __can__ include extra properties (this is the default behaviour and the same
109as pre 1.2)
110
111```
112var validation = swagger.validateModel("modelName", target, true, true);
113```
114
115### Added support for x-nullable required properties
116From 2.1.4 you can add a custom specification to allow a required object to be null.
117This is different from not being present in the body of the request or response.
118
119Simple add the property ```'x-nullable': true``` to your definition of a required property to allow the value of null to pass validation.
120This has no effect on any property that is not required.
121
122## Custom Field Validators
123You can add a custom field validator for a model to the validator from version 1.0.3 onwards. This allows you to add a
124function that will be called for any specific field that you need validated with extra rules.
125
126This function should be in the form
127```
128function(name, value) {
129 if(error) {
130 return new Error(error);
131 } else {
132 return null;
133 }
134}
135```
136It can return either a single Error object or an array of error objects. These errors will be passed back through the
137validator to the end user.
138
139### Adding a field validator
140Simply make a call to the validator method ```addFieldValidator``` providing the ```modelName```, ```fieldName``` and
141the validation function.
142
143```
144validator.addFieldValidator("testModel", "id", function(name, value) {
145 var errors = []
146 if(value === 34) {
147 errors.push(new Error("Value Cannot be 34"));
148 }
149
150 if(value < 40) {
151 errors.push(new Error("Value must be at least 40"));
152 }
153
154 return errors.length > 0 ? errors : null;
155});
156```
157Now the validator will call this extra function for the 'id' field in the 'testModel' model.
158
159You can add multiple custom validators to the same field. They will all be run. If a validator throws an exception it
160will be ignored and validation will continue.
161
162### Custom Field Validators for Swagger 2.0 Onwards
163Because the id property has been dropped from the model it is much harder to link models together in the validator.
164
165You can now add field validators as a custom property on each model by using the addFieldValidatorToModel function.
166
167```
168validator.addFieldValidatorToModel(model, "id", function(name, value) {
169 var errors = []
170 if(value === 34) {
171 errors.push(new Error("Value Cannot be 34"));
172 }
173
174 if(value < 40) {
175 errors.push(new Error("Value must be at least 40"));
176 }
177
178 return errors.length > 0 ? errors : null;
179});
180```
181
182## Handling Returned Errors
183Be careful with the results as javascript Errors cannot be turned into JSON without losing the message property.
184
185We have added two methods to help with this.
186
187GetErrorMessages() which returns an array of strings (one for each error) which contain the text of the error.message property.
188GetFormattedErrors() which returns an array of objects (one for each error) which contains all of the custom properties for each error and the text of the error.message property.
189
190Just passing the Validation Response errors array out will result in the loss of the error.message property. Most errors would appear as empty objects.
191
192## License
193Copyright (c) 2014 Atlantis Healthcare Limited.
194
195Permission is hereby granted, free of charge, to any person obtaining a copy
196of this software and associated documentation files (the "Software"), to deal
197in the Software without restriction, including without limitation the rights
198to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
199copies of the Software, and to permit persons to whom the Software is
200furnished to do so, subject to the following conditions:
201
202The above copyright notice and this permission notice shall be included in
203all copies or substantial portions of the Software.
204
205THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
206IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
207FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
208AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
209LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
210OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
211THE SOFTWARE.
212
\No newline at end of file