UNPKG

6.74 kBMarkdownView Raw
1# Validate incoming objects against Swagger Models for Node.js
2[ ![Codeship Status for atlantishealthcare/swagger-model-validator](https://codeship.io/projects/a4ec3310-3b9b-0132-060c-1e7e00028aa9/status)](https://codeship.io/projects/42728)
3
4This is a validation module for [Swagger](https://github.com/wordnik/swagger-spec) models Node.js.
5
6See the [swagger-node-express](https://github.com/wordnik/swagger-node-express/blob/master/SAMPLE.md) sample for more details about Swagger in Node.js.
7
8## What's Swagger?
9The 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.
10
11Check out [Swagger-Spec](https://github.com/wordnik/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more.
12
13## Validating Swagger Models?
14A 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.
15
16This package provides a module to do just that.
17
18### Validation Notes
19It will validate int32 properly but the way javascript handles int64 makes it impossible to accurately validate int64s.
20As long as the value can be parsed by parseInt in javascript it will be accepted as an int64.
21
22It currently treats float and decimal the same but this is because javascript cannot cope with a decimal (at the moment).
23As long as the value can be parsed by parseFloat in javascript it will be accepted as a float or a decimal.
24
25It validates the date and date-time correctly. It treats all dates (and date-times) as dates and tests with a parseDate
26check. If this passes then it checks 'date' format against a length of 10 (a quick check against the ISO8601 standard
27- a full-date must be 10 characters long).
28
29As from version 0.3 it will now validate models referenced by the $ref keyword but it will only do this if it is called
30by the swagger function validateModel or if the native validate is called with a model array passed in.
31
32As from version 1.0.0 it will now validate arrays in models. It will validate arrays of a type and arrays of a $ref.
33### Installation
34Install swagger-model-validator
35
36```
37npm install swagger-model-validator
38```
39
40Create a validator and pass your swagger client into it.
41```
42var Validator = require('swagger-model-validator');
43var validator = new Validator(swagger);
44```
45
46Now you can call validateModel on swagger to validate an incoming json object.
47
48```
49var validation = swagger.validateModel("modelName", jsonObject);
50```
51
52This returns a validation results object
53
54```
55{
56 valid: true,
57 errorCount: 0
58}
59```
60or if validation fails
61```
62{
63 valid: false,
64 errorCount: 2,
65 errors: [
66 {
67 name: 'Error',
68 message: 'An error occurred'
69 },
70 {
71 name: 'Error',
72 message: 'Another error occurred'
73 }
74 ]
75}
76```
77
78You can also call the validation directly
79
80```
81var validation = validator.validate(object, swaggerModel, swaggerModels);
82```
83
84will return the same validation results but requires the actual swagger model and not its name. _The swaggerModels
85parameter is required if you want models referenced by the $ref keyword to be validated as well._
86
87### Allowing blank targets to validate
88From 1.0.2 any empty objects passed in as targets will fail validation. You can bypass this by adding a `true` value to
89the method at the end.
90
91```
92var validation = swagger.validateModel("modelName", target, true);
93```
94
95This will allow an empty object `{ }` to be validated without errors. We consider a blank object to be worthless in most
96cases and so should normally fail, but there is always the chance that it might not be worthless so we've added the bypass.
97
98##Custom Field Validators
99You can add a custom field validator for a model to the validator from version 1.0.3 onwards. This allows you to add a
100function that will be called for any specific field that you need valdiated with extra rules.
101
102This function should be in the form
103```
104function(name, value) {
105 if(error) {
106 return new Error(error);
107 } else {
108 return null;
109 }
110}
111```
112It can return either a single Error object or an array of error objects. These errors will be passed back through the
113validator to the end user.
114
115### Adding a field validator
116Simply make a call to the validator method ```addFieldValidator``` providing the ```modelName```, ```fieldName``` and
117the validation function.
118
119```
120validator.addFieldValidator("testModel", "id", function(name, value) {
121 var errors = []
122 if(value === 34) {
123 errors.push(new Error("Value Cannot be 34"));
124 }
125
126 if(value < 40) {
127 errors.push(new Error("Value must be at least 40"));
128 }
129
130 return errors.length > 0 ? errors : null;
131});
132```
133Now the validator will call this extra function for the 'id' field in the 'testModel' model.
134
135You can add multiple custom validators to the same field. They will all be run. If a validator throws an exception it
136will be ignored and validation will continue.
137
138## License
139Copyright (c) 2014 Atlantis Healthcare Limited.
140
141Permission is hereby granted, free of charge, to any person obtaining a copy
142of this software and associated documentation files (the "Software"), to deal
143in the Software without restriction, including without limitation the rights
144to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
145copies of the Software, and to permit persons to whom the Software is
146furnished to do so, subject to the following conditions:
147
148The above copyright notice and this permission notice shall be included in
149all copies or substantial portions of the Software.
150
151THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
152IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
153FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
154AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
155LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
156OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
157THE SOFTWARE.
158
\No newline at end of file