All files / src/plugins/validation/oas3/semantic-validators discriminator.js

100% Statements 20/20
100% Branches 6/6
100% Functions 2/2
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                              29x 29x 29x 29x 29x   29x 57x   57x   57x   57x 91x 6x   6x 1x     5x   5x 5x 4x             4x       57x    
// Assertation 1:
// if discriminator exist inside schema object, it must be of type Object
// enforced by Spectral's oas3-schema rule
 
// Assertion 2:
// discriminator object must have a field name propertyName
// enforced by Spectral's oas3-schema rule
 
// Assertation 3:
// propertyName is of type string
// enforced by Spectral's oas3-schema rule
 
// Assertation 4:
// properties inside a schema object must include propertyName from discriminator object
 
const each = require('lodash/each');
const has = require('lodash/has');
const get = require('lodash/get');
const isPlainObject = require('lodash/isPlainObject');
const MessageCarrier = require('../../../utils/messageCarrier');
 
module.exports.validate = function({ jsSpec }) {
  const messages = new MessageCarrier();
 
  const schemas = get(jsSpec, ['components', 'schemas'], []);
 
  const basePath = ['components', 'schemas'];
 
  each(schemas, (schema, schemaName) => {
    if (has(schema, 'discriminator')) {
      const { discriminator } = schema;
 
      if (!isPlainObject(discriminator)) {
        return;
      }
 
      const { propertyName } = discriminator;
      // If the schema's property doesn't include propertyName defined in discriminator, add error and return
      const { properties } = schema;
      if (!has(properties, propertyName)) {
        messages.addMessage(
          basePath
            .concat([schemaName, 'discriminator', 'propertyName'])
            .join('.'),
          'The discriminator property name used must be defined in this schema',
          'error'
        );
        return;
      }
    }
  });
  return messages;
};