Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/support generate swagge for typescript (#608) #641

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion generate-swagger.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async function runFastify (opts) {
let file = null

try {
file = await requireServerPluginFromPath(opts._[0])
file = await requireServerPluginFromPath(opts._[0], { swagger: true })
} catch (e) {
return module.exports.stop(e)
}
Expand Down
1 change: 1 addition & 0 deletions generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const typescriptTemplate = {
scripts: {
test: 'npm run build:ts && tsc -p test/tsconfig.json && tap --ts "test/**/*.test.ts"',
start: 'npm run build:ts && fastify start -l info dist/app.js',
swagger: 'fastify generate-swagger ./src/app.ts',
'build:ts': 'tsc',
'watch:ts': 'tsc -w',
dev: 'npm run build:ts && concurrently -k -p "[{name}]" -n "TypeScript,App" -c "yellow.bold,cyan.bold" "npm:watch:ts" "npm:dev:start"',
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@
"standard": "^17.0.0",
"strip-ansi": "^6.0.1",
"tap": "^16.1.0",
"ts-node": "^10.4.0",
"ts-standard": "^12.0.1",
"tsd": "^0.16.0",
"typescript": "^4.5.4",
"walker": "^1.0.8"
"walker": "^1.0.8",
"ts-node": "^10.9.1"
},
"tsd": {
"directory": "test"
Expand Down
3 changes: 2 additions & 1 deletion test/generate-typescript.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ function define (t) {
})

test('should finish successfully with typescript template', async (t) => {
t.plan(25 + Object.keys(expected).length)
t.plan(26 + Object.keys(expected).length)
try {
await generate(workdir, typescriptTemplate)
await verifyPkg(t)
Expand All @@ -128,6 +128,7 @@ function define (t) {
t.ok(pkg.license === 'ISC' || pkg.license === 'MIT')
t.equal(pkg.scripts.test, 'npm run build:ts && tsc -p test/tsconfig.json && tap --ts "test/**/*.test.ts"')
t.equal(pkg.scripts.start, 'npm run build:ts && fastify start -l info dist/app.js')
t.equal(pkg.scripts.swagger, 'fastify generate-swagger ./src/app.ts')
t.equal(pkg.scripts['build:ts'], 'tsc')
t.equal(pkg.scripts['watch:ts'], 'tsc -w')
t.equal(pkg.scripts.dev, 'npm run build:ts && concurrently -k -p "[{name}]" -n "TypeScript,App" -c "yellow.bold,cyan.bold" "npm:watch:ts" "npm:dev:start"')
Expand Down
36 changes: 29 additions & 7 deletions util.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const url = require('url')
const semver = require('semver')
const pkgUp = require('pkg-up')
const resolveFrom = require('resolve-from')

const moduleSupport = semver.satisfies(process.version, '>= 14 || >= 12.17.0 < 13.0.0')

function exit (message) {
Expand All @@ -18,6 +17,27 @@ function exit (message) {

process.exit()
}
function serverTypeScriptPlugin (resolvedModulePath) {
const currentDir = process.cwd()
const tsconfigPath = path.join(currentDir, 'tsconfig.json')
if (!fs.existsSync(tsconfigPath)) {
throw new Error('The tsconfig.json file does not exist.')
}
const tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf8'))
const outDir = tsconfig.compilerOptions && tsconfig.compilerOptions.outDir
if (!outDir) {
throw new Error('The output directory (outDir) was not specified in tsconfig.json.')
}
const relativeToRootDir = path.relative(currentDir, resolvedModulePath)
const outDirRelativeToRootDir = relativeToRootDir.replace(/^[^/]+/, outDir).replace(/\.ts$/, '.js')
const modulePath = path.resolve(currentDir, outDirRelativeToRootDir)

if (!fs.existsSync(outDir)) {
throw new Error('The output directory (outDir) has not been built. Please run the "tsc" command to build it.')
}

return modulePath
}

function requireModule (moduleName) {
if (fs.existsSync(moduleName)) {
Expand Down Expand Up @@ -58,16 +78,20 @@ function getScriptType (fname, packageType) {
return (modulePattern.test(fname) ? 'module' : commonjsPattern.test(fname) ? 'commonjs' : packageType) || 'commonjs'
}

async function requireServerPluginFromPath (modulePath) {
const resolvedModulePath = path.resolve(process.cwd(), modulePath)
async function requireServerPluginFromPath (modulePath, opts = { swagger: false }) {
let resolvedModulePath = path.resolve(process.cwd(), modulePath)

if (!fs.existsSync(resolvedModulePath)) {
throw new Error(`${resolvedModulePath} doesn't exist within ${process.cwd()}`)
}

const packageType = await getPackageType(resolvedModulePath)

const type = getScriptType(resolvedModulePath, packageType)

if (opts.swagger && resolvedModulePath.endsWith('.ts')) {
resolvedModulePath = serverTypeScriptPlugin(resolvedModulePath)
}
let serverPlugin
if (type === 'module') {
if (moduleSupport) {
Expand All @@ -83,7 +107,6 @@ async function requireServerPluginFromPath (modulePath) {
throw new Error('Async/Await plugin function should contain 2 arguments. ' +
'Refer to documentation for more information.')
}

return serverPlugin
}

Expand All @@ -94,14 +117,13 @@ function showHelpForCommand (commandName) {
console.log(fs.readFileSync(helpFilePath, 'utf8'))
exit()
} catch (e) {
exit(`unable to get help for command "${commandName}"`)
exit(`unable to get help for command '${commandName}'`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this change?

}
}

function isKubernetes () {
// Detection based on https://kubernetes.io/docs/reference/kubectl/#in-cluster-authentication-and-namespace-overrides
return process.env.KUBERNETES_SERVICE_HOST !== undefined ||
fs.existsSync('/run/secrets/kubernetes.io/serviceaccount/token')
return process.env.KUBERNETES_SERVICE_HOST !== undefined || fs.existsSync('/run/secrets/kubernetes.io/serviceaccount/token')
}

module.exports = { isKubernetes, exit, requireModule, requireFastifyForModule, showHelpForCommand, requireServerPluginFromPath }