Skip to content

Instantly share code, notes, and snippets.

@manrueda
Created June 6, 2017 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manrueda/18a3edcbe4961c973f59ec18896c1b5c to your computer and use it in GitHub Desktop.
Save manrueda/18a3edcbe4961c973f59ec18896c1b5c to your computer and use it in GitHub Desktop.
Generate code from swagger source
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