Giter Site home page Giter Site logo

ystrauch / swagger-object-validator Goto Github PK

View Code? Open in Web Editor NEW
29.0 4.0 8.0 743 KB

Node-Module to validate your model against a swagger spec and receive in-depth error traces

JavaScript 29.70% TypeScript 70.30%
swagger-spec swagger swagger2 validation validator polymorphism

swagger-object-validator's Introduction

What?

Validate an Object against a given swagger (V2.0) API definition.

A swagger definition specifies an API with requests and data models, and there are a lot of compilers to create server and client skeletons. There are some tools that validate the requests that were sent to the server, but surprisingly there is a huge lack of (good) validators for response bodies.

Just test it quickly and be amazed:

Try it on RunKit

Why this and not some other tool?

The API is awesome, it gives you easy and full control over what's happening:

  • Every error has a detailed stack trace so you can find where and what is wrong easily
  • Stack traces are in a format that allows computer programs to understand what's wrong without parsing strings
  • You can add your own rules or ignore certain errors
  • Other tools do not like splitted specifications (via $ref)
  • Most other tools do not implement very special constraints (like regex, int32/int64, minItems...)

Features

Validation

The following swagger specifications are validated:

  • All the basic stuff like Numbers, Strings, Enums, Arrays, Objects
  • Required properties
  • Int32/Int64, Float/Double, Booleans
  • Dates and Date-Times
  • Maps (additionalProperties)
  • Inheritance (allOf)
  • Polymorphism (discriminator)
  • Custom polymorphism that uses enums
  • All kinds of references ($ref)

Flexible API

  • Load your swagger spec from a JSON/yaml file, the interwebs or load it yourself and do your stuff first
  • Validate your object either by name or by a specification object
  • Get useful stack traces of all the validation errors that occured
  • Stack traces are readable by both programs and humans
  • Need to add custom validation rules or ignore certain errors? No problem!
  • TypeScript support

Quick start

Please ensure that the swagger spec itself is valid to prevent unexpected errors, this module does not verify the spec itself.

Let's assume you got a pet from your pet store and want to validate it.

Using TypeScript

import * as SwaggerValidator from 'swagger-object-validator';
let validator = new SwaggerValidator.Handler('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml');

let pet = {
    id: 123,
    name: 'Doge'
};
validator.validateModel(pet, 'Pet', (err, result) => {
    console.log(result.humanReadable());
});

Using JavaScript

var swaggerValidator = require('swagger-object-validator');
var validator = new swaggerValidator.Handler('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml');

var pet = {
    id: 123,
    name: 'Doge'
};
validator.validateModel(pet, 'Pet', function (err, result) {
    console.log(result.humanReadable());
});

Both will print out "Valid", since they comply to the swagger specification.

Error Trace

So lets change our pet model to be invalid (the rest of the code remains the same):

var pet = {
    id: 'This is not a number',
    foo: 'bar',
    tag: [
        'This is an optional argument, but it',
        'Should be a String, not an Array of Strings'
    ]
}

Now it will print out:

Missing required property:
	 - At Pet/name

Type mismatch:
	 - At Pet/id
	 - Should be: "number"
	 - Is: "string"

Additional Property:
	 - At Pet/foo

Type mismatch:
	 - At Pet/tag
	 - Should be: "string"
	 - Is: "array"

This is the human readable error trace, because we called result.humanReadable(). It will print out a full path to the error, where each step is seperated with a slash. They come quite handy if you need to find an error in a very complex model, and they support array positions and polymorphism!

The human readable trace is just a rendered version of result.errors, which looks like this:

[
    {
        "errorType": "MISSING_REQUIRED_PROPERTY",
        "trace": [
            {
                "stepName": "Pet"
            },
            {
                "stepName": "name"
            }
        ]
    },
    {
        "errorType": "ADDITIONAL_PROPERTY",
        "trace": [
            {
                "stepName": "Pet"
            },
            {
                "stepName": "foo"
            }
        ]
    },
    {
        "trace": [
            {
                "stepName": "Pet"
            },
            {
                "stepName": "id"
            }
        ],
        "errorType": "TYPE_MISMATCH",
        "typeIs": "string",
        "typeShouldBe": "number"
    },
    {
        "trace": [
            {
                "stepName": "Pet"
            },
            {
                "stepName": "tag"
            }
        ],
        "errorType": "TYPE_MISMATCH",
        "typeIs": "array",
        "typeShouldBe": "string"
    }
]

Ways to load a specification

JSON/yaml/URL

You may load JSON or yaml files from your disk or from the interwebs. It doesn't matter!

import * as SwaggerValidator from 'swagger-object-validator';
let validator = new SwaggerValidator.Handler('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml');
// or
let validator = new SwaggerValidator.Handler('./petstore.yaml');
// or
let validator = new SwaggerValidator.Handler('./petstore.json');
// or
let petStore = require('./petstore.json');
let validator = new SwaggerValidator.Handler(petStore);

Without an entire swagger spec

Up to now we always loaded the complete Swagger Specification. Maybe you don't need that and already know the exact model spec? Just validate against a model spec directly:

import * as SwaggerValidator from 'swagger-object-validator';
let validator = new SwaggerValidator.Handler();

let spec = {
    type: "array",
    items: {
        type: "string"
    }
}

let model = ['1', '2'];
validator.validateModel(model, spec, (err, result) => {
    console.log(result.humanReadable());
});

Inline models / unnamed models

If you need to validate a model against a definition that is not part of the definitions section, you can fetch the model specification like so:

import * as SwaggerValidator from 'swagger-object-validator';
let validator = new SwaggerValidator.Handler('https://raw.githubusercontent.com/YStrauch/swagger-object-validator/master/test/specs/yaml/swagger.yaml');

// Fetch the unnamed model from i.e. a path
let schema = json.paths['/person'].post.parameters[0].schema

validator.validateModel({'name': 'Homer'}, schema).then(result => {
    console.log(result.humanReadable());
});

Config

You can hand in a configuration object. Before diving in each of them let's look over it quickly:

interface IValidatorConfig {
  // for relative $refs, defaults to './'
  partialsDir?: string;

  // allow additional properties not defined in the Spec, defaults to false
  allowAdditionalProperties?: boolean;

  // allow usage of x-nullable for properties, defaults to false
  allowXNullable?: boolean;

  // will not check for uniqueItems constraint if there are more than this many, defaults to 100
  disableUniqueItemsOver?: number;
  // suppresses the console warning when uniqueItems was disabled due to disableUniqueItemsOver, defaults to false
  suppressUniqueItemsWarning?: boolean;

  // disallow fetching of HTTP and HTTPS resources, both default to false
  disallowHttp?: boolean;
  disallowHttps?: boolean;

  // add custom validation rules (sync and async)
  customValidation?: (
    test: any,
    schema: Swagger.Schema,
    spec: Swagger.Spec,
    trace: Array<ITraceStep>,
    otherErrors: Array<ICustomValidationError>,
    resolve?: (validationErrors: ICustomValidationError[]) => void,
    reject?: (reason: string) => void
  ) => ICustomValidationError[] | void | undefined;

  // you can ignore certain errors
  ignoreError?: ( // cb to ignore errors
    error: IValidationError,
    value: any,
    schema: Swagger.Schema,
    spec: Swagger.Spec
  ) => boolean;
}

Partials directory for $ref

$ref gives you the possibility to split your specification across different files (or even servers). There are multiple types of $refs:

// internal $ref
$ref: '#/definitions/Pet'

// $ref to the interwebs
$ref: 'https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml#/definitions/Pet'

// relative $ref
$ref: './pet.json'

The last kind of $refs, the relative ones, uses process.cwd() to determine the absolute path. If you want those $refs to resolve to another directory, you may specify a base path:

let config = {
  partialsDir: '/some/path/'
}
let validator = new SwaggerValidator.Handler('spec.yml', config);

Disallowing HTTP or HTTPs

As described in the paragraph above Swagger allows references to the interwebs. If you do not want this you can set a corresponding option:

let config = {
  disallowHttp: true,
  disallowHttps: true
};
let validator = new Handler('http://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml', config);

Allowing Additional properties

By default, every property that is not specified within the swagger definition adds an ADDITIONAL_PROPERTY error to the stack. If you want to allow certain properties you can do that with the ignoreError function (see "Ignoring Errors" below), or you can allow all additional properties at once with a config entry:

let config: IValidatorConfig = {
    allowAdditionalProperties: true
};

Allowing x-nullable properties

A common extension for Swagger 2 is x-nullable, based on nullable from the OpenAPI 3 spec. This allows a property to be returned as null instead of the intended type.

By enabling this configuration, the x-nullable property is recognized and respected when validating types.

let config: IValidatorConfig = {
    allowXNullable: true
};

Limiting the Unique Items Constraint

Since version 1.4.0, this library implements the uniqueItems constraint. This constraint can be set on array specs to disallow duplicate items and emit a ConstraintViolation if needed.

Detecting duplicate items needs to compare all items pairwise, and since items can be of arbitrary depth, this could bring drastic performance bottlenecks when you have a big number of items (or very complex items).

To prevent the validator to get stuck on this, by default it will never validate arrays for uniqueness that have more than 100 elements. You can change that cap with the disableUniqueItemsOver in your validator config to accommodate your needs and hardware.

If the cap is exceeded, a console warning will be emitted by default. You can disable this warning by setting suppressUniqueItemsWarning to true in your validator config.

For example, if you want to validate unique lists of up to 300 elements, you can change the cap and disable warnings like so:

let config = {
  disableUniqueItemsOver: 300,
  suppressUniqueItemsWarning: true
}
let validator = new SwaggerValidator.Handler('spec.yml', config);

Just remember that the algorithm will scale exponentially in the number of items.

Ignoring errors

You may want to ignore certain errors. Let's assume you need some magic to allow a certain string to be valid on a field that should normally be a number (because of reasons):

let config: IValidatorConfig = {
    ignoreError: (error, value, schema, spec) => {
      // ignore type mismatches on Pet/id when a certain value occures
      return error.errorType === ValidationErrorType.TYPE_MISMATCH
        && error.trace[0].stepName === 'Pet'
        && error.trace[1].stepName === 'id'
        && schema.type === 'integer'
        && value === 'magicKeyThatWillBeAllowed';
    }
};
let validator = new Handler('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml', config);
let pet = {
  id: 'magicKeyThatWillBeAllowed',
  name: 'Doge'
};
validator.validateModel(pet, 'Pet', (err, result) => {
  console.log(result.humanReadable()); // valid

Custom validation rules

You may need to implement custom rules, for example you may want to ensure that a pet name always starts with an uppercase letter. (For that specific use case you should probably just use a "pattern" regex swagger rule but for the sake of documentation we forget about this)

let config: IValidatorConfig = {
    customValidation: (test, schema, spec, trace, otherErrors) => {
      // only validate Pet/name
      if (trace.length !== 2
        || trace[trace.length - 2].stepName !== 'Pet'
        || trace[trace.length - 1].stepName !== 'name') {
        // the property is not a pet name, so do not return any validation errors
        return [];
      }

      // no need to ensure that petName is actually a string, because this will be already done for you
      let firstChar = test.substr(0,1);
      if (firstChar !== firstChar.toUpperCase()) {
        return [
          // You may throw a custom error, where content is any type
          {
            errorType: ValidationErrorType.CUSTOM, // or 6 for JS
            trace: trace,
            content: 'Name must start with an uppercase letter'
          }
        ];
      }

      // pet starts with an uppercase, so do not return validation errors
      return [];
    }
  };

You may either return an array of errors, or if you need to do asynchronously magic, you can use the resolve callback (or the reject callback to throw a critical error). Make sure not to mix return and resolve though.

customValidation: (test, schema, spec, trace, otherErrors, resolve, reject) => {
  setTimeout(() => resolve([]), 100);
}

Important:

  • Swagger-Object-Validator will run its validation logic before your custom validation is called. If any validation error occur within that logic, your handler is not called. (Would be annoying if we had to check if the name is a string right?)
  • With great power comes great runtime exceptions. If you allow for example a string on an object field to pass, the Object validator will crash because it expects its input to be an object. This hook should be used with caution.
  • Normally you should not need to implement custom rules, because you will add constraints that are not specified within the specification. Think first if you may be better on with a regex experssion, a min/max or any other swagger constraint.

Polymorphism

Swagger-Object-Validator can work with two types of polymorphism.

Standard polymorphism

Medium is a superclass of Image and Video. The discriminator type can either be "Image" or "Video". This is the way swagger intended polymorphism.

Medium:
  required:
    - type
  properties:
    type:
      type: string
Image:
    required:
      - source
    allOf:
      - $ref: '#/definitions/Medium'
    properties:
      source:
        type: string
Video:
    required:
      - length
    allOf:
      - $ref: '#/definitions/Medium'
    properties:
      length:
        type: integer
let medium = {
  type: 'Image',
  source: 'source' // property only exists within image
};

// the plot in polymorphism is that you validate
// your model against the abstract Medium class,
// not against the concrete Image class
validator.validateModel(medium, 'Medium', (err, result) => {
  //...
});

Enum polymorphism

Instead of using the Name of the object, enum polymorphism uses enums to differentiate:

Section:
  required:
    - sectionType
  discriminator: sectionType
  properties:
    sectionType:
      type: string
      enum:
        - TEXT_SECTION
        - IMAGE_SECTION

TextSection:
  allOf:
    - $ref: '#/definitions/Section'
  properties:
    sectionType:
      type: string
      enum:
        - TEXT_SECTION
    textContent:
      type: string

ImageSection:
  required:
    - imageSource
  allOf:
    - $ref: '#/definitions/Section'
  properties:
    sectionType:
      type: string
      enum:
        - IMAGE_SECTION
    imageSource:
      type: string
let section = {
  sectionType: 'TEXT_SECTION',
  textContent: 'Custom polymorphed text section'
};

Polymorphism within the stack trace

The stack trace will tell you if polymorphism was detected. So if a Medium may be an Image, and Polymorphism was detected, a trace may look like this:

{
    "errors": [
        {
            "errorType": "MISSING_REQUIRED_PROPERTY",
            "trace": [
                {
                    "stepName": "Medium",
                    "concreteModel": "Image" // here
                },
                {
                    "stepName": "source"
                }
            ]
        }
    ]
}

HumanReadable:

Missing required property:
	 - At Medium<Image>/source

Potentially breaking Changes

1.3.0

  • Fixed typo, changed ValidationErrorType from 'CONSTRAINTS_VIOATION' to 'CONSTRAINTS_VIOLATION' (added missing L)
  • If you call validateModel() without a full-fledged spec (i.e. just the model definition), the first error step did previously not have a name. This was changed to the dedicated name 'root'.

1.4.0

  • The ValidationErrorType in result.model was changed from a numeric enum to a more verbose string enum. This will mainly affect JavaScript applications and their logic to handle specific validation errors. TypeScript applications should be unaffected if the enums were used as documented. The values changed from integers between 0 and 6 to 'MISSING_REQUIRED_PROPERTY', 'ADDITIONAL_PROPERTY', 'TYPE_MISMATCH', 'ENUM_MISMATCH', 'DATE_FORMAT', 'CONSTRAINTS_VIOLATION', and 'CUSTOM'. This deprecated errorsWithStringTypes.
  • Added support for uniqueItems. Please also read about the default cap of 100 items here.

Development

Technical Setup

Install node.js. Then run: npm install --global yarn; yarn install. Please make sure to use an IDE with TSLint and EditorConfig installed (i.e. Visual Studio Code).

Development

This project is entirely test-driven. You can run tests locally like this:

npm run-script watch:test # Build the application, run tests and watch the FS
npm run-script debug # Very useful to trace bugs. You need a remote debugging software, I use VSCode debugger

Tests need to have minimum code to test the desired effect. Don't include huge swagger specs.

Pull-Requests

Please ensure that your pull request includes tests that demonstrate the feature or bug fix and that your code conforms to the TSLint specifications in this project.

swagger-object-validator's People

Contributors

dependabot[bot] avatar khmmrl avatar ystrauch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

swagger-object-validator's Issues

custom ignoreError function causes another error to be thrown

Related to #8

As a workaround for the above issue, I added an ignoreError function to ignore cases where non-required fields were set to null.

Example (ES6):

var swaggerValidator = require('swagger-object-validator');
var validator = new swaggerValidator.Handler('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml',
  {
    allowAdditionalProperties: true,
    ignoreError: (error, value, schema, spec) => {
      // Set Ignore cases where non-required fields are set to null rather than specified type/format
      return error.errorType === swaggerValidator.ValidationErrorType.TYPE_MISMATCH &&
        !spec.definitions[error.trace[0].stepName].required.includes(error.trace[1].stepName) &&
        value === null;
    }
  });

var pet = {
  id: 3942394023,
  name: 'Pippin',
  tag: null
}

validator.validateModel(pet, 'Pet', function (err, result) {
  console.log(err);
});

However, rather than ignoring the error as I expected, it throws the following Error:

Type string not yet implemented (in undefined)

Thrown from at tryCatcher (node_modules/bluebird/js/release/util.js:16:23)
Originating (I think) from lib/validators/ModelValidator.js at line 53

Null value for non-required fields triggers error

When a model has a non-required field, and that value is set to null, this library still flags an error. For example:

var swaggerValidator = require('swagger-object-validator');
var validator = new swaggerValidator.Handler('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore.yaml');

var pet = {
  id: 3942394023,
  name: 'Pippin',
  tag: null
}

validator.validateModel(pet, 'Pet', function (err, result) {
  console.log(result.humanReadable()); //Type mismatch: - At Pet/tag - Should be: "string" - Is: "null"
});

If you leave the tag field out entirely, the validation passes. I'd like to be able to set an option to allow non-required field values to null.

Not validating number

When we use:

type: number
format: float

And try the number:

-1234.58

It returns a:

"Type mismatch:"

Is it correct?

Using the module on the frontend (webpack) causes warnings

I love the idea of this library.

I'm trying to use it client side to validate my objects against the swagger definitions before posting them to the server.

The first issue I ran into is this error:

ERROR in ./~/swagger-object-validator/lib/helpers/loader.js
Module not found: Error: Can't resolve 'fs' in '/project/node_modules/swagger-object-validator/lib/helpers'
 @ ./~/swagger-object-validator/lib/helpers/loader.js 3:13-26

I got rid of it by including the following in my webpack config:

    node: {
      fs: 'empty'
    },

I would rather not have to add that though.

The second issue is that now that I have it running I still get the following warning both from my webpack console and in my javascript console:

WARNING in ./~/swagger-object-validator/lib/helpers/loader.js
105:57-70 Critical dependency: the request of a dependency is an expression

I'm using [email protected] and [email protected]

Let me know if you want to see any more of my configuration.

uniqueItems property

Is it supported?

import * as SwaggerValidator from 'swagger-object-validator';
let validator = new SwaggerValidator.Handler();
 
let spec = {
    type: "array",
    uniqueItems: true,
    items: {
        type: "string",
        enum: ["1" ,"2", "3", "4"]
    }
}
 
let model = ['1', '2', '1']; // Should not be valid
validator.validateModel(model, spec, (err, result) => {
    console.log(result.humanReadable());
});

Oh.....found it:


if (schema.uniqueItems) {
--
37 | console.warn('WARNING: uniqueItems not supported (you found literally the only swagger feature that is currently unsupported)');


Missing ./configuration-interfaces/validator-config.d

In the last release v1.1.0, it's missing for me the following file in the lib folder, after a NPM INSTALL:
node_modules/swagger-object-validator/lib/handler.d.ts(3,34): error TS2307: Cannot find module './configuration-interfaces/validator-config.d'.

After adding the following file by hand, everything is alright.

Could you help us with this issue?

'Non-absolute path found' error

Hi there!

I've just updated to version 1.4.3 and started to receive these errors.
Downgrading to 1.4.0 helps (.1 and .2 seems to have the same problem)

Relative path I'm using seems to work as intended in 1.4.0:
var validator = new swaggerValidator.Handler('logs-schema.yaml', {allowAdditionalProperties : true});

Absolute paths still work in 1.4.3 though

Error stacktrace:
Error: Non-absolute path found, internal logic should have converted relative paths to absolute at _loadFromString (/Users/kirillburton/.../node_modules/swagger-object-validator/lib/helpers/loader.js:98:19) at loader (/Users/kirillburton/.../node_modules/swagger-object-validator/lib/helpers/loader.js:23:16) at new Handler (/Users/kirillburton/.../node_modules/swagger-object-validator/lib/handler.js:29:48) at Object.<anonymous> (/Users/kirillburton/.../swagger-test-test.js:2:17) at Module._compile (internal/modules/cjs/loader.js:759:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10) at Module.load (internal/modules/cjs/loader.js:628:32) at Function.Module._load (internal/modules/cjs/loader.js:555:12) at Function.Module.runMain (internal/modules/cjs/loader.js:826:10) at internal/main/run_main_module.js:17:11

Support for Swagger 3.0

Is this library being developed? Are there any plans to support swagger 3.0?
We need an object validator for new OpenAPI specs, I'm willing to contribute, but it would be useful to get some guidance.
Thanks

Cannot find module './specs' or its corresponding type declarations

When using the module with TypeScript, two files are not found and the following output is generated:

node_modules/swagger-object-validator/lib/handler.d.ts(2,32): error TS2307: Cannot find module './specs' or its corresponding type declarations.
node_modules/swagger-object-validator/lib/handler.d.ts(3,34): error TS2307: Cannot find module './validator-config' or its corresponding type declarations.

This is due to the two files being ".d.ts" files, which are not copied over in the current typescript setup.

Clarify it only validates definitions

Hi, thanks for this library, is quite cool.

It would be nice if it could be clarified, in the README, that this library only validates definitions, not paths and not JSON full responses, for instance.

I'm looking for a full JSON response validation per path, please let me know if you know of something like that.

Validate nested arrays throws exception

Great package, using flawlessly except one problem.
Cannot validate pure array schema, had to wrap around in an object for now

Schema

{
  type: "array",
  "x-nullable": false,
  items: {
    type: "array",
    items: {
      type: "string",
      minLength: 1,
    },
  },
  description: "nested arrays"
}

Validation

validator.validateModel(
      [
        ['1'],['2']
      ],
     schema,

Error

TypeError: Cannot set property 'arrayPos' of undefined
    at /Users/node_modules/swagger-object-validator/lib/validators/ArrayValidator.js:40:48
    at Array.forEach (<anonymous>)
    at validateArray (/Users/node_modules/swagger-object-validator/lib/validators/ArrayValidator.js:38:10)
    at /Users//node_modules/swagger-object-validator/lib/validators/ModelValidator.js:58:29
From previous event:
    at Object.validateModel (/Users/node_modules/swagger-object-validator/lib/validators/ModelValidator.js:26:10)
    at /Users/node_modules/swagger-object-validator/lib/handler.js:46:67
From previous event:
    at /Users/node_modules/swagger-object-validator/lib/handler.js:46:18

Schema not defined in "definitions"

Validation did not occur like following case not defined in definitions.

  /person:
    post:
      summary: sample
      operationId: Person
      parameters:
        - name: Person
          in: body
          required: true
          schema:
            properties:
              name:
                type: string
                minLength: 2
                maxLength: 5
            required:
              - name
      responses:
        200:
          description: ok

Polymorphism Support

Hi guy,
first of all, congratulations for your job with this library and thanks.
I'm using this with a big and complicated model and i've 2 object with Polymorphism, one inside the other, apparently swagger UI is OK but when i send a property of inside element appear an error:

- Additional Property:
- At Asset/content[0]/elements[0]/htmlContent

This is a summary of the definitions to my swagger:

definitions:
  Asset:
      content:
        type: array
        items:
          $ref: '#/definitions/Zone'

  Zone:
    description: >
      Zone Schema.
    properties:
      name: 
        type: string
      elements:
        type: array
        items:
            $ref: '#/definitions/Element'
  Element:
    description: >
      Element Schema.
    required:
      - id
      - active
      - elementType
    discriminator: elementType
    properties:
      id:
        type: integer
        format: int64
      active:
        type: boolean
      elementType:
        type: string
        description: Element type name
        enum:
          - video
          - extension

  Video:
    description: >
      Video (Element) Schema.
    allOf:
      - $ref: '#/definitions/Element'
    properties:
      elementType:
        type: string
        enum:
          - video
      caption:
        type: string

  Extension:
    description: >
      Extension (Element) Schema.
    required:
      - extensionType    
    allOf:
      - $ref: '#/definitions/Element'
    discriminator: extensionType
    properties:
      elementType:
        type: string
        enum:
          - extension
      extensionType:
        type: string
        enum:
          - videoExtension
          - photoExtension
      title:
        type: string
      description:
        type: string

  VideoExtension:
    description: >
      VideoExtension Schema.
    allOf:
      - $ref: '#/definitions/Extension'
    properties:
      elementType:
        type: string
        enum:
          - extension
      extensionType:
        type: string
        enum:
          - videoExtension
      htmlContent:
        type: string

  VideoExtension:
    description: >
      VideoExtension Schema.
    allOf:
      - $ref: '#/definitions/Extension'
    properties:
      elementType:
        type: string
        enum:
          - extension
      extensionType:
        type: string
        enum:
          - photoExtension
      image:
        type: string

I suppose that not posible do this or i do something wrong, do you have any idea?

Thanks, regards.

Models using allOf not working as expected

I use inheritance to build models, as seems to be a common pattern in Swagger. A good example is the 'Pet' model from the Swagger documentation's expanded petstore example - Pet inherits the fields from NewPet.

definitions:
  Pet:
    allOf:
      - $ref: '#/definitions/NewPet'
      - required:
        - id
        properties:
          id:
            type: integer
            format: int64

  NewPet:
    required:
      - name  
    properties:
      name:
        type: string
      tag:
        type: string  

However, using the following example code, this library throws an error

Schema is corrupted (no schema/type), schema is {"allOf":[{"$ref":"#/definitions/NewPet"},{"required":["id"],"properties":{"id":{"type":"integer","format":"int64"}}}]}

The expected result would be a validation error due to the non-integer value for id.

var swaggerValidator = require('swagger-object-validator');
var validator = new swaggerValidator.Handler('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/yaml/petstore-expanded.yaml');

var pet = {
  id: 'not an integer',
  name: 'Pippins'
}

validator.validateModel(pet, 'Pet', function (err, result) {
  console.log(result.humanReadable());
});

es5-compatible release?

First, thanks for your work -- this library was just what I needed.
Unfortunately, the current es6 release cannot be handled by uglify-js (used by current create-react-app), and thus it fails the build. Any chance you could publish an es5-transpiled version to npm?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.