Created
June 6, 2017 18:50
-
-
Save manrueda/18a3edcbe4961c973f59ec18896c1b5c to your computer and use it in GitHub Desktop.
Generate code from swagger source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const swaggerExtractor = /https?:\/\/(.*)\/.*\/#!\/(.*)\/(.*)/i | |
function getUrlsParts (url) { | |
const [, domain, entity, method] = url.match(swaggerExtractor) | |
return { domain, entity, method } | |
} | |
async function getModels(url) { | |
const { domain, entity, method } = getUrlsParts(url) | |
const req = await fetch(`https://${domain}/api/core/swagger/api-docs/${entity}`) | |
const jsonResponse = await req.json() | |
const postMethod = jsonResponse.apis.map(a => a.operations.filter(o => o.nickname === method)[0]).filter(a => a)[0] | |
const bodyType = postMethod.parameters.filter(p => p.paramType === 'body')[0].type | |
return { mainType: bodyType, models: jsonResponse.models} | |
} | |
async function init(swaggerUrl) { | |
const { mainType, models } = await getModels(swaggerUrl) | |
console.log(generateCSharpClass(models[mainType])) | |
} | |
function generateCSharpClass(model) { | |
let header = `public class ${model.typeName} {` | |
let body = '' | |
Object.keys(model.properties).forEach(key => { | |
const prop = model.properties[key] | |
if (prop.type === 'array') { | |
body += `\tpublic Array<${prop.items.$ref}> ${prop.typeName} { get; set; }\n` | |
} else { | |
body += `\tpublic ${prop.type || prop.$ref} ${prop.typeName} { get; set; }\n` | |
} | |
}) | |
let footer = '}' | |
return [header, body, footer].join('\n') | |
} | |
init('URLt') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment