Skip to content

Commit

Permalink
feat: can get swagger file from url
Browse files Browse the repository at this point in the history
fix #4
  • Loading branch information
Val-istar-Guo committed May 11, 2021
1 parent 8d9854d commit 3f64462
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"eslint": "^7.20.0",
"husky": "^5.1.1",
"is-ci": "^2.0.0",
"keq": "^1.2.1",
"keq": "^1.2.2",
"lint-staged": "^10.5.4",
"mili": "^3.9.3",
"nyc": "^15.1.0",
Expand All @@ -74,7 +74,8 @@
"openapi-types": "^8.0.0",
"ramda": "^0.27.1",
"semver": "^7.3.5",
"ts-custom-error": "^3.2.0"
"ts-custom-error": "^3.2.0",
"valid-url": "^1.0.9"
},
"version": "1.0.3",
"directories": {
Expand Down
31 changes: 24 additions & 7 deletions src/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,33 @@ import * as yaml from 'js-yaml'
import * as path from 'path'
import { genModuleCode } from './gencode'
import { Options } from './interface'
import validUrl from 'valid-url'
import { request } from 'keq'


export async function compile(moduleName: string, filepath: string, options: Options): Promise<void> {
const fileext = path.extname(filepath)
const content = await fs.readFile(filepath, 'utf8')
if (['.yml', '.yaml'].includes(fileext)) {
await genModuleCode(moduleName, yaml.load(content), options)
} else if (fileext === '.json') {
await genModuleCode(moduleName, JSON.parse(content), options)
if (validUrl.isUri(filepath)) {
const res = await request
.get(filepath)
.option('resolveWithFullResponse')

let content = await res.text()
try {
content = JSON.parse(content)
} catch (e) {
throw new Error(`The swagger file get from url isn't json: ${filepath}`)
}

await genModuleCode(moduleName, content, options)
} else {
throw new Error(`File ${fileext} not support.`)
const fileext = path.extname(filepath)
const content = await fs.readFile(filepath, 'utf8')
if (['.yml', '.yaml'].includes(fileext)) {
await genModuleCode(moduleName, yaml.load(content), options)
} else if (fileext === '.json') {
await genModuleCode(moduleName, JSON.parse(content), options)
} else {
throw new Error(`File ${fileext} not support.`)
}
}
}

0 comments on commit 3f64462

Please sign in to comment.