diff --git a/lib/codegen.js b/lib/codegen.js index 504a45ef..9e638f11 100644 --- a/lib/codegen.js +++ b/lib/codegen.js @@ -30,6 +30,41 @@ var getPathToMethodName = function(opts, m, path){ return m.toLowerCase() + result[0].toUpperCase() + result.substring(1); }; +const mergeObjectWithValue = (query, parameters) => { + return Object.keys(parameters).reduce((toSearch, key) => { + let merge = Object.assign({}, toSearch); + if (undefined === parameters[key]) { + merge = Object.assign(merge, {[key]: parameters[key]}); + } + return merge; + }, Object.assign({}, query)); +}; + +const isRequired = function (property, required, collectionRequired) { + + return (required) ? collectionRequired.concat(property) : collectionRequired; +}; + +const getSchema = function (type, property) { + const enumValue = property.enum || undefined; + const defaultValue = property.default || undefined; + const {pattern, title} = property || {}; + + let parameter = {type}; + parameter = mergeObjectWithValue(parameter, {default: defaultValue, pattern, enum: enumValue, title}); + if ('string' === type) { + const { minLength, maxLength } = property; + parameter = mergeObjectWithValue(parameter, {minLength, maxLength}); + } else if ('integer' === type) { + const { minimum, maximum } = property; + parameter = mergeObjectWithValue(parameter, {minimum, maximum}); + } else if ('array' === type) { + const { items, maxItems, minItems, uniqueItems } = property; + parameter = mergeObjectWithValue(parameter, {items, maxItems, minItems, uniqueItems}); + } + + return parameter; +}; var getDefaultDomain = function(swagger) { var domain = swagger.schemes[0]; domain += '://'; @@ -69,8 +104,9 @@ var getViewForSwagger2 = function(opts, type){ imports: opts.imports, domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host) ? getDefaultDomain(swagger) : '', methods: [], - definitions: [] - }; + definitions: [], + schemas: [] + }; var secureTypesGlobal = validateSecurity(swagger.securityDefinitions, swagger.security); @@ -204,6 +240,31 @@ var getViewForSwagger2 = function(opts, type){ }; method.parameters.push(parameter); }); + let schemaForm = {}; + let collectionRequired = []; + method.parameters.filter(element => 'body' === element.in || 'query' === element.in).forEach((element) => { + const {required} = element; + if (element.hasOwnProperty('schema')) { + const {schema: {properties = {}}} = element; + Object.keys(properties).forEach(name => { + const {type} = properties[name]; + schemaForm[name] = getSchema(type, data); + collectionRequired = isRequired(name, required, collectionRequired); + }); + } else { + const {type, name} = element; + schemaForm[name] = getSchema(type, element); + collectionRequired = isRequired(name, required, collectionRequired); + } + }); + + if (!_.isEmpty(schemaForm)) { + data.schemas.push({ + id: methodName, schema: JSON.stringify( + {required: collectionRequired, properties: schemaForm, type: 'object'} + ) + }); + } data.methods.push(method); }); });