| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- import SwaggerParser from 'swagger-parser'
- export const parseApiDocFile = async (remoteUrl: string) => {
- let apiDoc
- try {
- // @ts-ignore
- apiDoc = await SwaggerParser.parse(remoteUrl)
- } catch (e) {
- console.error('[parse api doc failed]', e)
- }
- return apiDoc
- }
- export const isJsonString = (input: string) => {
- return input ? /^\{\s*".+}$/.test(input.trim()) : false
- }
- export const formatJsonString = (input: string) => {
- let formatted: string
- try {
- formatted = JSON.stringify(JSON.parse(input), null, 2)
- } catch (e) {
- formatted = input.trim()
- }
- return formatted
- }
- const convertKeyValuePropertiesToArray = (obj: any) => {
- if (!obj || !Object.keys(obj).length) {
- return null
- }
- const params: any[] = []
- if (obj) {
- for (const key in obj) {
- const row = obj[key]
- if (row.properties || row.items && row.items.properties) {
- row.children = convertKeyValuePropertiesToArray(row.properties || row.items.properties)
- }
- params.push({
- name: key,
- ...row
- })
- }
- }
- return params
- }
- export const formatApiDocToRoutes = (data: any, opts?: {
- injectAccessKey?: boolean
- }) => {
- const {
- host = '',
- basePath = '',
- schemes,
- paths
- } = data
- const {
- injectAccessKey = true
- } = opts || {}
- const routes: any[] = []
- if (paths) {
- let index = 0
- for (const path in paths) {
- for (const method in paths[path]) {
- const item = paths[path][method]
- const url = `${schemes[schemes.length -1]}://${host}${basePath}${path}`.replace(/\/+$/, '')
- const paramsMap: any = {}
- let successResponse: any
- if (injectAccessKey) {
- paramsMap.query = [{
- name: 'key',
- in: 'query',
- description: '请求 AccessKey, 请在控制台中查看',
- required: true,
- type: 'string',
- _certif: true
- }]
- }
- if (item.parameters && item.parameters.length) {
- for (const param of item.parameters) {
- // header, path, query, body
- const _in = param.in
- if (!_in) {
- continue
- }
- if (!paramsMap[_in]) {
- paramsMap[_in] = []
- }
- paramsMap[_in].push(param)
- }
- }
- if (item.responses) {
- for (const code in item.responses) {
- const schema = item.responses[code].schema
- if (/^20/.test(code) && schema) {
- successResponse = {
- schema,
- params: convertKeyValuePropertiesToArray(schema.properties),
- example: schema.example
- }
- break
- }
- }
- }
- routes.push({
- index,
- url,
- method,
- paramsMap,
- successResponse,
- ...item
- })
- index++
- }
- }
- }
- return routes
- }
|