All files index.js

78.38% Statements 87/111
78.87% Branches 56/71
80.77% Functions 21/26
77.98% Lines 85/109
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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236                    7x                       7x 19x     19x 19x 19x     19x     45x   7x 124x 21x 10x 11x 2x       2x   9x 103x 20x   96x     7x   48x 48x     7x       122x 48x   74x     7x 53x 3x     50x 3x     47x 2x     45x           45x       122x         122x             7x 15x 15x     7x     47x 2x   45x 3x   6x 6x 1x   6x   3x     42x 14x   28x     7x   10x 9x 1x 1x   10x       10x   45x       45x     45x     45x     10x     7x 10x 10x 10x     7x               7x 2x   7x                       7x 2x 2x 2x     7x 2x   7x 2x       2x 2x     7x               7x                                  
#! /usr/bin/env node
// @flow
import program from "commander";
import prettier from "prettier";
import yaml from "js-yaml";
import fs from "fs";
import path from "path";
import axios from "axios";
 
// Swagger data types are base on types supported by the JSON-Scheme Draft4.
const typeMapping = {
  array: "Array<*>",
  boolean: "boolean",
  integer: "number",
  number: "number",
  null: "null",
  object: "Object",
  Object: "Object",
  string: "string",
  enum: "string"
};
 
const definitionTypeName = (ref): string => {
  Iif (!ref) {
    return "";
  }
  const re = /#\/definitions\/(.*)|#\/components\/schemas\/(.*)/;
  const found = ref.match(re);
  Iif (!found) {
    return "";
  }
  return found[1] || found[2];
};
 
const stripBrackets = (name: string) => name.replace(/[[\]']+/g, "");
 
const typeFor = (property: any): string => {
  if (property.type === "array") {
    if ("$ref" in property.items) {
      return `Array<${definitionTypeName(property.items.$ref)}>`;
    } else if (property.items.type === "object") {
      const child = propertiesTemplate(propertiesList(property.items)).replace(
        /"/g,
        ""
      );
      return `Array<${child}>`;
    }
    return `Array<${typeMapping[property.items.type]}>`;
  } else if (property.type === "string" && "enum" in property) {
    return property.enum.map(e => `'${e}'`).join(" | ");
  }
  return typeMapping[property.type] || definitionTypeName(property.$ref);
};
 
const isRequired = (propertyName: string, definition: Object): boolean => {
  const result =
    definition.required && definition.required.indexOf(propertyName) >= 0;
  return result;
};
 
const propertyKeyForDefinition = (
  propName: string,
  definition: Object
): string => {
  if (program.checkRequired) {
    return `${propName}${isRequired(propName, definition) ? "" : "?"}`;
  }
  return propName;
};
 
const propertiesList = (definition: Object) => {
  if ("allOf" in definition) {
    return definition.allOf.map(propertiesList);
  }
 
  if (definition.$ref) {
    return { $ref: definitionTypeName(definition.$ref) };
  }
 
  if ("type" in definition && definition.type !== "object") {
    return typeFor(definition);
  }
 
  Iif (
    !definition.properties ||
    Object.keys(definition.properties).length === 0
  ) {
    return {};
  }
  return Object.assign.apply(
    null,
    Object.keys(definition.properties).reduce(
      (properties: Array<Object>, propName: string) => {
        const arr = properties.concat({
          [propertyKeyForDefinition(propName, definition)]: typeFor(
            definition.properties[propName]
          )
        });
        return arr;
      },
      [{}]
    )
  );
};
 
const withExact = (property: string): string => {
  const result = property.replace(/{[^|]/g, "{|").replace(/[^|]}/g, "|}");
  return result;
};
 
const propertiesTemplate = (
  properties: Object | Array<Object> | string
): string => {
  if (typeof properties === "string") {
    return properties;
  }
  if (Array.isArray(properties)) {
    return properties
      .map(property => {
        let p = property.$ref ? `& ${property.$ref}` : JSON.stringify(property);
        if (!property.$ref && program.exact) {
          p = withExact(p);
        }
        return p;
      })
      .sort(a => (a[0] === "&" ? 1 : -1))
      .join(" ");
  }
  if (program.exact) {
    return withExact(JSON.stringify(properties));
  }
  return JSON.stringify(properties);
};
 
const generate = (swagger: Object): string => {
  let defs;
  if (swagger.definitions) {
    defs = swagger.definitions;
  } else Eif (swagger.components) {
    defs = swagger.components.schemas;
  }
  Iif (!defs) {
    throw new Error("There is no definition");
  }
 
  const g = Object.keys(defs)
    .reduce((acc: Array<Object>, definitionName: string) => {
      const arr = acc.concat({
        title: stripBrackets(definitionName),
        properties: propertiesList(defs[definitionName])
      });
      return arr;
    }, [])
    .map(definition => {
      const s = `export type ${definition.title} = ${propertiesTemplate(
        definition.properties
      ).replace(/"/g, "")};`;
      return s;
    })
    .join(" ");
  return g;
};
 
export const generator = (content: Object) => {
  const options = {};
  const result = `// @flow\n${generate(content)}`;
  return prettier.format(result, options);
};
 
export const writeToFile = (dist: string = "./flowtype.js", result: string) => {
  fs.writeFile(dist, result, err => {
    if (err) {
      throw err;
    }
  });
};
 
export const isUrl = (value: string): boolean =>
  value.match(/https?:\/\//) !== null;
 
export const distFile = (p: Object, inputFileName: string): string => {
  if (p.destination) {
    return p.destination;
  }
  if (isUrl(inputFileName)) {
    return "./flowtype.js";
  }
 
  const ext = path.parse(inputFileName).ext;
  return inputFileName.replace(ext, ".js");
};
 
export const getContentFromFile = (file: string): Object => {
  const ext = path.extname(file);
  const readFile = fs.readFileSync(file, "utf8");
  return ext === ".yaml" ? yaml.safeLoad(readFile) : JSON.parse(readFile);
};
 
export const isObject = (value: any): boolean =>
  typeof value === "object" && value !== null;
 
export const getContentFromUrl = (url: string): Promise<Object> =>
  axios({
    method: "get",
    url
  }).then(response => {
    const { data } = response;
    return isObject(data) ? data : yaml.safeLoad(data);
  });
 
export const getContent = (fileOrUrl: string): Promise<Object> => {
  if (isUrl(fileOrUrl)) {
    return getContentFromUrl(fileOrUrl);
  }
  const content = getContentFromFile(fileOrUrl);
  return Promise.resolve(content);
};
 
program
  .arguments("<file>")
  .option("-d --destination <destination>", "Destination path")
  .option("-cr --check-required", "Add question mark to optional properties")
  .option("-e --exact", "Add exact types")
  .action(async file => {
    try {
      const content = await getContent(file);
      const result = generator(content);
      const dist = distFile(program, file);
      writeToFile(dist, result);
      console.log(`Generated flow types to ${dist}`);
    } catch (e) {
      console.log(e);
    }
  })
  .parse(process.argv);