Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.