Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const API = require('../spec/openapi.json');
  2.  
  3. const findOperation = (operationId) => {
  4.   const { paths } = API;
  5.  
  6.   for (let url in paths) {
  7.     const path = paths[url];
  8.  
  9.     for (let method in path) {
  10.       const operation = path[method];
  11.  
  12.       if (operation.operationId === operationId) return operation;
  13.     }
  14.   }
  15.  
  16.   return false;
  17. };
  18.  
  19. const findSchema = (schemaName) => {
  20.   const { components: { schemas } } = API;
  21.  
  22.   for (let schemaKey in schemas) {
  23.     if (schemaKey === schemaName) return schemas[schemaKey];
  24.   }
  25.  
  26.   return false;
  27. };
  28.  
  29. const getTransformedSchema = (schema) => {
  30.   const transformedSchema = {
  31.     properties: {},
  32.     required: []
  33.   };
  34.  
  35.   for (let key in schema.properties) {
  36.     const property = schema.properties[key];
  37.  
  38.     transformedSchema.properties[key] = {
  39.       type: property.type
  40.     };
  41.   }
  42.  
  43.   for (let key in schema.required) {
  44.     transformedSchema.required.push(schema.required[key]);
  45.   }
  46.   return transformedSchema;
  47. };
  48.  
  49. /**
  50.  * Parses API specification and tries to find Schema by operationId
  51.  * @param operationId
  52.  * @return {boolean|Object}
  53.  */
  54. const fromRequestBody = (operationId) => {
  55.   const operation = findOperation(operationId);
  56.   if (
  57.     !operation ||
  58.     !operation['requestBody'] ||
  59.     !operation['requestBody']['content'] ||
  60.     !operation['requestBody']['content']['application/json'] ||
  61.     !operation['requestBody']['content']['application/json']['schema'] ||
  62.     !operation['requestBody']['content']['application/json']['schema']['properties']
  63.   ) return false;
  64.  
  65.   const schema = operation['requestBody']['content']['application/json']['schema'];
  66.  
  67.   return getTransformedSchema(schema);
  68. };
  69.  
  70. /**
  71.  * Parses API specification and tries to find Schema by schemaName
  72.  * @param schemaName
  73.  * @return {boolean|Object}
  74.  */
  75. const fromComponentsSchemas = (schemaName) => {
  76.   const schema = findSchema(schemaName);
  77.   if (
  78.     !schema
  79.   ) return false;
  80.  
  81.   return getTransformedSchema(schema);
  82. };
  83.  
  84. module.exports = {
  85.   fromRequestBody,
  86.   fromComponentsSchemas
  87. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement