Created
May 8, 2019 08:10
-
-
Save webislife/2a83a05f5fab94ab92b18aea02615548 to your computer and use it in GitHub Desktop.
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
/* eslint-disable */ | |
const ejs = require('ejs'), | |
path = require('path'), | |
request = require('request'), | |
fs = require('fs'), | |
resolvePath = p => path.resolve(__dirname, p); | |
let specCompiled = false; | |
class CodegenPlugin { | |
constructor(options) { | |
this.options = options; | |
} | |
fetchAPI(alias) { | |
const apiHost = this.options.APP_CONF.API_BGLN_HOST + "swagger/json/v4/"; | |
console.log('Start generate spec from:', apiHost); | |
console.time('generate-api'); | |
return new Promise((resolve, reject) => { | |
if(specCompiled === true) { | |
resolve(); | |
} else { | |
request({ url: apiHost, json: true}, | |
(err, res, body) => { | |
if (!err && res.statusCode === 200) { | |
console.log('Swagger api spec received \r', Object.keys(body.paths)); // Print the json responsex | |
//Generate axios instance API methods | |
ejs.renderFile(resolvePath('./templates/api-instance.ejs'), { | |
paths: body.paths, | |
}, {}, function(err, str) { | |
if(err) { | |
throw new Error(err); | |
} | |
//Save for server | |
fs.writeFileSync(alias['@server'] + '/routes/bgln/swagger.js', str); | |
console.log(alias['@server'] + '/routes/bgln/swagger.js', '- saved'); | |
//Save for client | |
fs.writeFileSync(alias['@client'] + '/api/biglion/swagger.js', str); | |
console.log(alias['@client'] + '/api/biglion/swagger.js', '- saved'); | |
console.timeEnd('generate-api'); | |
specCompiled = true; | |
resolve(); | |
}); | |
console.time('route-api'); | |
//Generate router instance API methods | |
//@TODO доделать когда бекенд реализует спецификацию. | |
// ejs.renderFile(resolvePath('./templates/router-instance.ejs'), { | |
// paths: body.paths | |
// }, {}, function(err, str) { | |
// if(err) throw new Error(err); | |
// fs.writeFileSync(resolvePath("./router.js"), str); | |
// console.timeEnd('route-api'); | |
// resolve(true) | |
// }); | |
} else { | |
reject('Swagger host unavailable ', apiHost, 'Build spec api failed'); | |
} | |
} | |
); | |
} | |
}); | |
} | |
apply(compiler) { | |
compiler.hooks.beforeRun.tapPromise( | |
'CodegenPlugin', | |
compile => this.fetchAPI(compiler.options.resolve.alias), | |
err => console.error(err)); | |
} | |
} | |
module.exports = CodegenPlugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment