Skip to content

Instantly share code, notes, and snippets.

@stipsan
Last active February 5, 2018 11:05
Show Gist options
  • Save stipsan/77de06507d74442c82916477f2d59722 to your computer and use it in GitHub Desktop.
Save stipsan/77de06507d74442c82916477f2d59722 to your computer and use it in GitHub Desktop.
fun test

Transform API Blueprints to TypeScript Definitions

How to use

Prerequisites: node v8, docker run is available and npx exists.

  1. In your terminal cd to the folder where your compiled.apib is.
  2. Execute docker run -i bugyik/apib2json < compiled.apib | npx https://gist.github.com/stipsan/77de06507d74442c82916477f2d59722 > api.d.ts. The first time it runs it might take a little time to download the docker image but subsequent runs should be quick.
  3. Load the generated typings 😉 perhaps using /// <reference path="../api.d.ts" />
  4. Then in your resolvers: const {body}: {body: RestEndpoints.GetUserResponse} = await got(endpoint)
  5. As you type body. vscode will autocomplete it for you with whatever that endpoint is offering.
#!/usr/bin/env node
const getStdin = require('get-stdin')
const { compile } = require('json-schema-to-typescript')
const { format } = require('prettier')
const moduleName = process.argv[2] || 'RestEndpoints'
const typeDef = (root, name) =>
compile(root.schema, name.replace(/[\[\]\/]/g, ' ') + ' ' + root.meta.type, {
bannerComment: '',
declareExternallyReferenced: false
})
getStdin().then(async str => {
const schemas = JSON.parse(str)
const endpoints = Object.keys(schemas)
const interfaces = await Promise.all(
endpoints.map(async endpoint => {
const defs = []
defs.push(await typeDef(schemas[endpoint][0], endpoint.split('?')[0]))
if (schemas[endpoint][1] && schemas[endpoint][0].meta.type !== schemas[endpoint][1].meta.type) {
defs.push(await typeDef(schemas[endpoint][1], endpoint.split('?')[0]))
}
return defs.join('\n').replace(/\[k: string\]: any;/g, '')
})
)
const declaration = [
'// This file is automatically generated!',
'',
`declare module ${JSON.stringify(moduleName)}`,
'{',
...interfaces,
'}'
].join('\n')
console.log(
format(declaration, {
parser: 'typescript',
singleQuote: true,
semi: false
}).trim()
)
})
{
"name": "apib2ts",
"version": "0.0.0",
"bin": "./index.js",
"dependencies": {
"get-stdin": "5.0.1",
"json-schema-to-typescript": "5.3.2",
"prettier": "1.10.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment