Skip to content

Commit

Permalink
feat: 新增swagger生成的本舰标记,修复action参数的导入
Browse files Browse the repository at this point in the history
  • Loading branch information
kongjing@dian.so authored and kongjing@dian.so committed Nov 7, 2022
1 parent aa07940 commit be91552
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 18 deletions.
2 changes: 2 additions & 0 deletions packages/api/global.d.ts
Expand Up @@ -10,6 +10,8 @@ declare module '*.json' {
const value: any
export default value
}
// 定义接口的方案类型:前端代码定义、服务端swagger定义
type IApiType = 'FRONT' | 'SWAGGER'

declare namespace NodeJS {
interface ProcessEnv {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/bin.ts
Expand Up @@ -39,7 +39,7 @@ program
.option('-p, --path <path>', 'request types path')
.option('-u, --url <url>', 'the url of swagger data')
.option('-mod, --modules <modules>', 'swagger tag item split with comma')
.option('-a, --actions <actions>', 'if create request method')
.option('-a, --action <action>', 'if create request method')
.action(swagger)

program.parse(process.argv)
2 changes: 1 addition & 1 deletion packages/api/src/create-action/create.ts
Expand Up @@ -14,7 +14,7 @@ export function createDefaultModel({
if (key !== 'Record<string,any>' && item.url && item.description) {
packages.push(key)
requestActionsStr += `
// ${item.description}
// ${item.description || '暂无描述'}
export const ${
key +
fileName.replace(/^\S/, function (s) {
Expand Down
78 changes: 64 additions & 14 deletions packages/api/src/file.ts
Expand Up @@ -23,19 +23,14 @@ if (fs.existsSync(API_UI_DATA_PATH)) {
}

export function workFile(targetUrl: string, action: boolean) {
const globPaths = [`${targetUrl}/*.ts`, `${targetUrl}/ **/*.ts`]
const globPaths = [`${targetUrl}/*.ts`, `${targetUrl}/**/*.ts`]
const writeActionTarget = path_.resolve(targetUrl, dirPath || '../')
if (!fs.existsSync(writeActionTarget)) {
fs.mkdirSync(writeActionTarget)
}

return new Promise((resolve) => {
globMax(globPaths, async (err, paths: string[]) => {
if (err) {
log.error(err.toString())
process.exit(1)
}

globMax(globPaths, async (paths: string[]) => {
await workUnit(paths, action, writeActionTarget)

if (!fs.existsSync(path_.join(CWD, './.cache'))) {
Expand Down Expand Up @@ -106,6 +101,8 @@ function workUnit(paths: string[], action: boolean, writeActionTarget: string) {
for (let i = 0; i < paths.length; i++) {
const p = paths[i]
if (p) {
const fileCode = fs.readFileSync(p, 'utf-8')
const apiTypeComments = getApiTypeComments(fileCode)
const parseRes = parser(p)
const fileArr = p.split('/')
const fileName = fileArr[fileArr.length - 1]?.replace('.ts', '')
Expand Down Expand Up @@ -133,10 +130,14 @@ function workUnit(paths: string[], action: boolean, writeActionTarget: string) {

const prettierConfig = await getPrettierConfig()

const formatContent = prettier.format(content, {
...prettierConfig,
parser: 'typescript',
})
const formatContent = prettier.format(
`${apiTypeComments}
${content}`,
{
...prettierConfig,
parser: 'typescript',
},
)

fs.writeFileSync(
path_.resolve(writeActionTarget, `${fileName}.ts`),
Expand All @@ -156,19 +157,68 @@ function workUnit(paths: string[], action: boolean, writeActionTarget: string) {
}

async function globMax(files, callback) {
let allPaths: string[] = []
const allPaths: string[] = []
for (let i = 0; i < files.length; i++) {
const pats = await globSync(files[i])
if (pats) allPaths = allPaths.concat(pats)
pats.forEach((it) => {
if (!allPaths.includes(it)) {
allPaths.push(it)
}
})
}

callback(allPaths)
}

async function globSync(file): Promise<string[]> {
return new Promise((resolve, reject) => {
glob(file, (err, pats) => {
if (err) reject(err)
if (err) {
console.info(err, '????')
reject(err)
}
resolve(pats)
})
})
}

function getApiTypeComments(codeStr: string) {
const commentsMatch = codeStr.match(/\/\*\*[\w\W]{4,100}\*\//)
let comments = '/** @type front */'
if (commentsMatch) {
const commentsStr = commentsMatch[0]
const comm: Record<string, any> = parseComments(commentsStr)
if (comm['type'].includes('swagger')) {
comments = '/** @type from swagger */'
}
}

return comments
}

function parseComments(comments = '') {
const res = {}
if (comments && comments.includes('\n')) {
const arr = comments
.split('\n')
.filter((item) => item.includes('@'))
.map((item) => item.replace(/^[\s]+/g, ''))
.map((item) => item.replace('* ', ''))
.map((item) => item.replace('@', ''))
.map((item) => item.replace(/[\s]+/, '##'))

arr.forEach((item) => {
const cons = item.split('##')
if (cons[0]) res[cons[0]] = cons[1]
})
} else if (comments) {
const arr = comments
.replace(/\/\*\*[\s]*/, '')
.replace(/[\s]*\*\//, '')
.replace('@', '')
.split(' ')
if (arr[0]) res[arr[0]] = arr[1]
}

return res
}
6 changes: 4 additions & 2 deletions packages/api/src/swagger/transform.ts
Expand Up @@ -20,6 +20,8 @@ const DEAULT_RESPONSE = `{
*/
success: boolean
}`
const API_TYPE_COMMENTS = `/** @type swagger(标注swagger生成的代码,请确认后修改) */
`

export async function transform(
data: Record<string, any>,
Expand Down Expand Up @@ -134,7 +136,7 @@ export async function transform(
`
await fs.writeFileSync(
pat.join(typesUrl, `${createTypeFileName?.(nn)}.ts`),
formatTs(`${baseImport}${mode.codes}`),
formatTs(`${API_TYPE_COMMENTS}${baseImport}${mode.codes}`),
)
}
/** todo 只生成使用的基础类型 */
Expand Down Expand Up @@ -406,7 +408,7 @@ function createComments(params?: Record<string, any>) {

function resetRepeatName(name) {
if (/[0-9]{1,4}$/g.test(name)) {
let words = name.replace(/[0-9]{1,4}$/g, '')
const words = name.replace(/[0-9]{1,4}$/g, '')
let num = name.match(/[0-9]{1,4}$/g)[0] || 0

num = Number(num) + 1
Expand Down

0 comments on commit be91552

Please sign in to comment.