Skip to content
This repository has been archived by the owner on Feb 28, 2020. It is now read-only.

feat: model support for swagger #422

Merged
merged 2 commits into from
Jan 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 92 additions & 37 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ var format = require('util').format
var fs = require('fs')
var path = require('path')
var url = require('url')
var Promise = require('bluebird')
var request = require('request')
var requestAsync = Promise.promisify(request)
var YAML = require('js-yaml')
var chalk = require('chalk')

// Keywords which are reserved in Swift (taken from the Language Reference)
Expand Down Expand Up @@ -535,48 +531,107 @@ exports.getBluemixDefaultPlan = function (serviceType) {
}
}

function loadHttpAsync (uri) {
debug('in loadHttpAsync')
// take a swagger path and convert the parameters to Swift Kitura format.
// i.e. convert "/path/to/{param1}/{param2}" to "/path/to/:param1/:param2"
exports.reformatPathToSwiftKitura = (path) => path.replace(/{/g, ':').replace(/}/g, '')

return requestAsync({ method: 'GET', uri: uri })
.then(result => {
if (result.statusCode !== 200) {
debug('get request returned status:', result.statusCode)
throw new Error(chalk.red('failed to load swagger from:', uri, 'status:', result.statusCode))
}
return result.body
})
exports.resourceNameFromPath = function (thepath) {
// grab the first valid element of a path (or partial path) and return it capitalized.
var resource = thepath.match(/^\/*([^/]+)/)[1]
return resource.charAt(0).toUpperCase() + resource.slice(1)
}

function loadFileAsync (filePath, memfs) {
debug('in loadFileAsync')
exports.getRefName = function (ref) {
return ref.split('/').pop()
}

return Promise.try(() => memfs.read(filePath))
.then(data => {
if (data === undefined) {
// when file exists but cannot read content.
debug('cannot read file contents', filePath)
throw new Error(chalk.red('failed to load swagger from:', filePath))
}
return data
})
exports.capitalizeFirstLetter = function (toBeCapitalized) {
// capitalize the first letter
return toBeCapitalized.charAt(0).toUpperCase() + toBeCapitalized.slice(1)
}

exports.loadAsync = function (path, memfs) {
var isHttp = /^https?:\/\/\S+/.test(path)
var isYaml = (path.endsWith('.yaml') || path.endsWith('.yml'))
return (isHttp ? loadHttpAsync(path) : loadFileAsync(path, memfs))
.then(data => isYaml ? JSON.stringify(YAML.load(data)) : data)
exports.arrayContains = function (search, array) {
return array.indexOf(search) > -1
}

// take a swagger path and convert the parameters to Swift Kitura format.
// i.e. convert "/path/to/{param1}/{param2}" to "/path/to/:param1/:param2"
exports.reformatPathToSwiftKitura = (path) => path.replace(/{/g, ':').replace(/}/g, '')
exports.swiftTypeFromSwaggerProperty = function (property) {
// return a Swift type based on a swagger type and format.
var swaggerPropertyTypes = [
'boolean',
'integer',
'number',
'string'
]

var swaggerToSwiftInt = {
'int8': 'Int8',
'uint8': 'UInt8',
'int16': 'Int16',
'uint16': 'UInt16',
'int32': 'Int32',
'uint32': 'UInt32',
'int64': 'Int64',
'uint64': 'UInt64'
}

exports.resourceNameFromPath = function (thepath) {
// grab the first valid element of a path (or partial path) and return it capitalized.
var resource = thepath.match(/^\/*([^/]+)/)[1]
return resource.charAt(0).toUpperCase() + resource.slice(1)
var swaggerToSwift = {
boolean: 'Bool',
integer: 'Int',
number: 'Double',
string: 'String',
object: 'Dictionary<String, JSONValue>'
}

var format
var array
var mappingType
var swiftType

if (property.type) {
if (exports.arrayContains(property.type, swaggerPropertyTypes)) {
swiftType = swaggerToSwift[property.type]
format = property.format || undefined
} else if (property.type === 'ref' && property.$ref) {
swiftType = exports.getRefName(property.$ref)
format = undefined
} else if (property.type === 'object') {
if (property.additionalProperties && property.additionalProperties.type) {
swiftType = swaggerToSwift[property.additionalProperties.type]
format = property.additionalProperties.format || undefined
mappingType = true
}
} else if (property.type === 'array') {
if (property.items.$ref) {
// has a ref type, so set the swagger type to that.
swiftType = exports.getRefName(property.items.$ref)
} else if (property.items && property.items.type) {
swiftType = swaggerToSwift[property.items['type']]
format = property.items['format'] || undefined
}
array = true
}
}

// now check if the property has a format modifier and apply that if appropriate.
if (format) {
// a format modifier exists, so convert the swagger type if appropriate.
if (swiftType === 'Int') {
swiftType = swaggerToSwiftInt[format]
}

if (swiftType === 'Double' && format === 'float') {
swiftType = 'Float'
}
}

if (mappingType) {
swiftType = 'Dictionary<String, ' + swiftType + '>'
}

if (array) {
swiftType = '[' + swiftType + ']'
}
return swiftType
}

exports.isThisServiceAnArray = function (serviceType) {
Expand Down
4 changes: 1 addition & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"generator-ibm-service-enablement": "0.6.4",
"generator-ibm-usecase-enablement": "3.2.0",
"handlebars": "^4.0.5",
"ibm-openapi-support": "^0.0.9",
"ibm-openapi-support": "0.0.10",
"js-yaml": "^3.9.1",
"request": "^2.81.0",
"rimraf": "^2.5.2",
Expand Down
84 changes: 74 additions & 10 deletions refresh/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ module.exports = Generator.extend({
}

if (this.openApiFileOrUrl) {
return helpers.loadAsync(this.openApiFileOrUrl, this.fs)
return swaggerize.loadAsync(this.openApiFileOrUrl, this.fs)
.then(loaded => {
this.openApiDocumentBytes = loaded
})
Expand All @@ -756,6 +756,15 @@ module.exports = Generator.extend({
.then(response => {
this.loadedApi = response.loaded
this.parsedSwagger = response.parsed
// mangle the route name to allow the renaming of the default route.
Object.keys(this.parsedSwagger.resources).forEach(resource => {
debug('RESOURCENAME:', resource)
if (resource.endsWith('*')) {
this.parsedSwagger.resources[resource]['generatedName'] = resource.replace(/\*$/, 'Default')
} else {
this.parsedSwagger.resources[resource]['generatedName'] = resource + '_'
}
})
})
.catch(err => {
if (this.openApiFileOrUrl) {
Expand All @@ -770,15 +779,18 @@ module.exports = Generator.extend({

addEndpointInitCode: function () {
var endpointNames = []
if (this.parsedSwagger && this.parsedSwagger.resources) {
var resourceNames = Object.keys(this.parsedSwagger.resources)
endpointNames = endpointNames.concat(resourceNames)
}
if (this.healthcheck) {
this.modules.push('"Health"')
endpointNames.push('Health')
this.dependencies.push('.package(url: "https://github.com/IBM-Swift/Health.git", from: "0.0.0"),')
}
if (this.parsedSwagger && this.parsedSwagger.resources) {
var resourceNames = []
Object.keys(this.parsedSwagger.resources).forEach(resource => {
resourceNames.push(this.parsedSwagger.resources[resource].generatedName)
})
endpointNames = endpointNames.concat(resourceNames)
}

var initCodeForEndpoints = endpointNames.map(name => `initialize${name}Routes(app: self)`)
this.appInitCode.endpoints = this.appInitCode.endpoints.concat(initCodeForEndpoints)
Expand Down Expand Up @@ -813,7 +825,7 @@ module.exports = Generator.extend({
function generateServerAsync () {
var sdkPackages = []
return Promise.map(this.serverSwaggerFiles, file => {
return helpers.loadAsync(file, this.fs)
return swaggerize.loadAsync(file, this.fs)
.then(loaded => {
return swaggerize.parse(loaded, helpers.reformatPathToSwift)
.then(response => {
Expand Down Expand Up @@ -1011,20 +1023,72 @@ module.exports = Generator.extend({

createFromSwagger: function () {
if (this.parsedSwagger) {
handlebars.registerHelper('swifttype', helpers.swiftTypeFromSwaggerProperty)
Object.keys(this.parsedSwagger.resources).forEach(resource => {
debug(resource)
// Generate routes
var generatedName = this.parsedSwagger.resources[resource].generatedName
debug('route:', this.parsedSwagger.resources[resource])
this.fs.copyHbs(
this.templatePath('fromswagger', 'Routes.swift.hbs'),
this.destinationPath('Sources', this.applicationModule, 'Routes', `${resource}Routes.swift`),
this.destinationPath('Sources', this.applicationModule, 'Routes', `${generatedName}Routes.swift`),
{
resource: resource,
resource: generatedName,
routes: this.parsedSwagger.resources[resource],
basepath: this.parsedSwagger.basepath
}
)
})

// make the swagger available for the swaggerUI
// Generate model structures
Object.keys(this.parsedSwagger.models).forEach(name => {
var model = this.parsedSwagger.models[name]
var fileName = helpers.capitalizeFirstLetter(name + '.swift')
debug('model:', model)
debug('fileName:', fileName)

if (!model.id) {
model.id = name
}
// For Array of items/models referenced as part of definitions, no need
// generate a model file.
if (model.type === 'array' && model.items) {
return
}
if (model.properties) {
debug('model.properties', model.properties)
Object.keys(model.properties).forEach(prop => {
if (model.properties[prop].$ref) {
model.properties[prop]['type'] = 'ref'
}
if (model.required && !helpers.arrayContains(prop, model.required)) {
model.properties[prop]['optional'] = '?'
}
if (model.properties[prop].description && model.properties[prop].description.length > 0) {
if (model.properties[prop].description.match(/\n/)) {
console.log('found:', model.properties[prop].description)
}
// model.properties[prop].description = '// ' + model.properties[prop].description
var comments = model.properties[prop].description.split('\n')
if (comments[comments.length - 1].length === 0) {
comments = comments.slice(0, comments.length - 1)
}
model.properties[prop].description = comments
}
})
this.fs.copyHbs(
this.templatePath('fromswagger', 'Model.swift.hbs'),
this.destinationPath('Sources', this.applicationModule, 'Models', fileName),
{
properties: model.properties,
model: name,
required: model.required || [],
id: name,
license: this.license
})
}
})

// Make the swagger available for the swaggerUI
var swaggerFilename = this.destinationPath('definitions', `${this.projectName}.yaml`)
this.fs.write(swaggerFilename, YAML.safeDump(this.loadedApi))
}
Expand Down
14 changes: 7 additions & 7 deletions refresh/templates/common/InitializationError.swift
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import Foundation

public struct InitializationError: Error {
let message: String
init(_ msg: String) {
message = msg
}
let message: String
init(_ msg: String) {
message = msg
}
}

extension InitializationError: LocalizedError {
public var errorDescription: String? {
return message
}
public var errorDescription: String? {
return message
}
}
6 changes: 3 additions & 3 deletions refresh/templates/common/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import <%- applicationModule %>

do {

HeliumLogger.use(LoggerMessageType.info)
HeliumLogger.use(LoggerMessageType.info)

let app = try App()
try app.run()
let app = try App()
try app.run()

} catch let error {
Log.error(error.localizedDescription)
Expand Down
29 changes: 29 additions & 0 deletions refresh/templates/fromswagger/Model.swift.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{{!--
* Copyright IBM Corporation 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
--}}
{{license}}

public struct {{model}}: Codable {
{{#each properties}}
{{#if this.description}}

{{#each this.description}}
/// {{{this}}}
{{/each}}
{{/if}}
let {{@key}}: {{{swifttype this}}}{{this.optional}}
{{/each}}
}
Loading