index.js 5.58 KB
Newer Older
1 2 3 4 5
const memoizee = require('memoizee');
const utils = require('./utils');
const primitives = require('./preimitives');

const getDateByName = (name, parentsKey) => {
邓晓峰's avatar
邓晓峰 committed
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
  if (!name || name.length < 1) {
    return 'string';
  }
  if (Array.isArray(name)) {
    return getDateByName([...name].pop(), name);
  }
  if (['nickname', 'name'].includes(name)) {
    return 'cname';
  }
  if (['owner', 'firstName', 'lastName', 'username'].includes(name)) {
    return 'name';
  }
  if (['avatar'].includes(name)) {
    return 'avatar';
  }
  if (['group'].includes(name)) {
    return 'group';
  }
  if (name.toLocaleLowerCase().endsWith('id')) {
    return 'uuid';
  }
  if (
    name.toLocaleLowerCase().endsWith('type') ||
    name.toLocaleLowerCase().endsWith('key') ||
    ['key'].includes(name)
  ) {
    return 'id';
  }
  if (name.toLocaleLowerCase().endsWith('label') || ['label'].includes(name)) {
    const newParents = [...parentsKey];
    newParents.pop();
    const newType = getDateByName(newParents);
    if (newType !== 'string' && newType !== 'csentence') {
      return newType;
    }
    return 'label';
  }
  if (['email'].includes(name)) {
    return 'email';
  }
  if (['password'].includes(name)) {
    return 'string(16)';
  }
  if (['phone'].includes(name)) {
    return 'phone';
  }
  if (['province'].includes(name)) {
    return 'province';
  }
  if (['city'].includes(name)) {
    return 'city';
  }
  if (['addr', 'address'].includes(name)) {
    return 'county';
  }
  if (['country'].includes(name)) {
    return 'country';
  }
  if (
    ['url', 'imageUrl', 'href'].includes(name) ||
    name.toLocaleLowerCase().endsWith('url') ||
    name.toLocaleLowerCase().endsWith('urls') ||
    name.toLocaleLowerCase().endsWith('image') ||
    name.toLocaleLowerCase().endsWith('link')
  ) {
    return 'href';
  }
  if (name.toLocaleLowerCase().endsWith('errorcode')) {
    return 'errorCode';
  }
  if (
    ['type', 'status'].includes(name) ||
    name.toLocaleLowerCase().endsWith('status') ||
    name.toLocaleLowerCase().endsWith('type')
  ) {
    return 'status';
  }
  if (name.toLocaleLowerCase().endsWith('authority')) {
    return 'authority';
  }
  return 'csentence';
};
88 89

function primitive(schemaParams, propsName) {
邓晓峰's avatar
邓晓峰 committed
90 91 92 93 94 95 96 97 98
  const schema = utils.objectify(schemaParams);
  const { type, format } = schema;
  const value =
    primitives[`${type}_${format || getDateByName(propsName)}`] ||
    primitives[type];
  if (typeof schema.example === 'undefined') {
    return value || `Unknown Type: ${schema.type}`;
  }
  return schema.example;
99 100
}
class OpenAPIGeneratorMockJs {
邓晓峰's avatar
邓晓峰 committed
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
  constructor(openAPI) {
    this.sampleFromSchema = (schema, propsName) => {
      const localSchema = schema.$ref
        ? utils.get(this.openAPI, schema.$ref.replace('#/', '').split('/'))
        : utils.objectify(schema);
      let { type } = localSchema;
      const { properties, additionalProperties, items } = localSchema;
      if (!type) {
        if (properties) {
          type = 'object';
        } else if (items) {
          type = 'array';
        } else {
          return null;
        }
      }
      if (type === 'object') {
        const props = utils.objectify(properties);
        const obj = {};
        // eslint-disable-next-line guard-for-in
        for (const name in props) {
          obj[name] = this.sampleFromSchema(props[name], [
            ...(propsName || []),
            name,
          ]);
        }
        if (additionalProperties === true) {
          obj.additionalProp1 = {};
          return obj;
        }
        if (additionalProperties) {
          const additionalProps = utils.objectify(additionalProperties);
          const additionalPropVal = this.sampleFromSchema(
            additionalProps,
            propsName,
          );
          for (let i = 1; i < 4; i += 1) {
            obj[`additionalProp${i}`] = additionalPropVal;
          }
        }
        return obj;
      }
      if (type === 'array') {
        const item = this.sampleFromSchema(items, propsName);
        return new Array(parseInt((Math.random() * 20).toFixed(0), 10)).fill(
          item,
        );
      }
      if (localSchema.enum) {
        if (localSchema.default) return localSchema.default;
        return utils.normalizeArray(localSchema.enum)[0];
      }
      if (type === 'file') {
        return null;
      }
      return primitive(localSchema, propsName);
    };
    this.parser = () => {
      // eslint-disable-next-line no-shadow
      const openAPI = {
        ...this.openAPI,
      };
      // eslint-disable-next-line guard-for-in
      for (const path in openAPI.paths) {
        // eslint-disable-next-line guard-for-in
        for (const method in openAPI.paths[path]) {
          const api = openAPI.paths[path][method];
          // eslint-disable-next-line guard-for-in
          for (const code in api.responses) {
            const response = api.responses[code];
            const schema =
              response.content &&
              response.content['application/json'] &&
              utils.inferSchema(response.content['application/json']);
            if (schema) {
              response.example = schema ? this.sampleFromSchema(schema) : null;
177
            }
邓晓峰's avatar
邓晓峰 committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191
          }
          // eslint-disable-next-line no-continue
          if (!api.parameters) continue;
          for (const parameter of api.parameters) {
            const schema = utils.inferSchema(parameter);
            parameter.example = schema ? this.sampleFromSchema(schema) : null;
          }
        }
      }
      return openAPI;
    };
    this.openAPI = openAPI;
    this.sampleFromSchema = memoizee(this.sampleFromSchema);
  }
192 193
}

邓晓峰's avatar
邓晓峰 committed
194
module.exports = OpenAPIGeneratorMockJs;