Skip to content

Instantly share code, notes, and snippets.

@jonaskuske
Created September 18, 2019 15:12
Show Gist options
  • Save jonaskuske/2a81fc976dc8730e75e742fba95ccb15 to your computer and use it in GitHub Desktop.
Save jonaskuske/2a81fc976dc8730e75e742fba95ccb15 to your computer and use it in GitHub Desktop.
Extract a TypeScript type from a Swagger Spec website
/* Used to extract a from a Swagger API spec */
function generateTypeScriptInterface(targetDef, definitions) {
if (typeof targetDef === 'string') {
definitions =
definitions ||
window.__defs__ ||
(window.__defs__ = JSON.parse(document.querySelector('body pre').textContent).definitions);
targetDef = definitions[targetDef];
}
if (!targetDef) throw Error('No valid type found!');
const body = JSON.stringify(
Object.fromEntries(
Object.entries(targetDef.properties).map(([propName, typeDef]) => [
propName,
typeDef.type === 'integer'
? 'number'
: typeDef.type
? typeDef.type === 'array'
? `${typeDef.items.type || typeDef.items.$ref}[]`
: typeDef.type === 'string'
? typeDef.enum
? typeDef.enum.map(i => `'${i}'`).join('|')
: 'string'
: typeDef.type
: typeDef.$ref,
]),
),
)
.replace(/#\/definitions\//g, '')
.replace(/"?(')"?/g, '$1')
.replace(/"(string|number|boolean)"/g, '$1');
return `export interface ${targetDef.title} ${body}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment