All files / src/plugins/validation/2and3/semantic-validators operation-ids.js

100% Statements 51/51
100% Branches 28/28
100% Functions 9/9
100% Lines 51/51

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152        29x 29x 29x 29x 29x   29x 91x   91x   91x                     91x     192x 269x   192x 192x 265x                       192x         91x                   79x   79x   38x 9x     29x 18x 18x       41x 21x     20x 4x     16x 3x     13x 8x 5x       5x 4x       79x 64x 82x 69x 64x     15x     91x   265x             239x 239x         548x     239x 79x             79x 13x                           91x    
// Assertation 1: Operations must have a unique operationId.
 
// Assertation 2: OperationId must conform to naming conventions.
 
const pickBy = require('lodash/pickBy');
const reduce = require('lodash/reduce');
const merge = require('lodash/merge');
const each = require('lodash/each');
const MessageCarrier = require('../../../utils/messageCarrier');
 
module.exports.validate = function({ resolvedSpec }, config) {
  const messages = new MessageCarrier();
 
  config = config.operations;
 
  const validOperationKeys = [
    'get',
    'head',
    'post',
    'put',
    'patch',
    'delete',
    'options',
    'trace'
  ];
 
  const operations = reduce(
    resolvedSpec.paths,
    (arr, path, pathKey) => {
      const pathOps = pickBy(path, (obj, k) => {
        return validOperationKeys.indexOf(k) > -1;
      });
      const allPathOperations = Object.keys(pathOps);
      each(pathOps, (op, opKey) =>
        arr.push(
          merge(
            {
              pathKey: `${pathKey}`,
              opKey: `${opKey}`,
              path: `paths.${pathKey}.${opKey}`,
              allPathOperations
            },
            op
          )
        )
      );
      return arr;
    },
    []
  );
 
  const operationIdPassedConventionCheck = (
    opKey,
    operationId,
    allPathOperations,
    pathEndsWithParam
  ) => {
    // Only consider paths for which
    // - paths that do not end with param has a GET and POST operation
    // - paths that end with param has a GET, DELETE, POST, PUT or PATCH.
 
    const verbs = [];
 
    if (!pathEndsWithParam) {
      // operationId for GET should starts with "list"
      if (opKey === 'get') {
        verbs.push('list');
      }
      // operationId for POST should starts with "create" or "add"
      else if (opKey === 'post') {
        verbs.push('add');
        verbs.push('create');
      }
    } else {
      // operationId for GET should starts with "get"
      if (opKey === 'get') {
        verbs.push('get');
      }
      // operationId for DELETE should starts with "delete"
      else if (opKey === 'delete') {
        verbs.push('delete');
      }
      // operationId for PATCH should starts with "update"
      else if (opKey === 'patch') {
        verbs.push('update');
      }
      // If PATCH operation doesn't exist for path, POST operationId should start with "update"
      else if (opKey === 'post') {
        if (!allPathOperations.includes('patch')) {
          verbs.push('update');
        }
      }
      // operationId for PUT should starts with "replace"
      else if (opKey === 'put') {
        verbs.push('replace');
      }
    }
 
    if (verbs.length > 0) {
      const checkPassed = verbs
        .map(verb => operationId.startsWith(verb))
        .some(v => v);
      return { checkPassed, verbs };
    }
 
    return { checkPassed: true };
  };
 
  operations.forEach(op => {
    // wrap in an if, since operationIds are not required
    if (op.operationId) {
      // Assertation 2: OperationId must conform to naming conventions
 
      // We'll use a heuristic to decide if this path is part of a resource oriented API.
      // If path ends in path param, look for corresponding create/list path
      // Conversely, if no path param, look for path with path param
 
      const pathEndsWithParam = op.pathKey.endsWith('}');
      const isResourceOriented = pathEndsWithParam
        ? Object.keys(resolvedSpec.paths).includes(
            op.pathKey.replace('/\\{[A-Za-z0-9-_]+\\}$', '')
          )
        : Object.keys(resolvedSpec.paths).some(p =>
            p.startsWith(op.pathKey + '/{')
          );
 
      if (isResourceOriented) {
        const { checkPassed, verbs } = operationIdPassedConventionCheck(
          op['opKey'],
          op.operationId,
          op.allPathOperations,
          pathEndsWithParam
        );
 
        if (checkPassed === false) {
          messages.addMessage(
            op.path + '.operationId',
            `operationIds should follow naming convention: operationId verb should be ${verbs}`.replace(
              ',',
              ' or '
            ),
            config.operation_id_naming_convention,
            'operation_id_naming_convention'
          );
        }
      }
    }
  });
 
  return messages;
};