Swet – parser is introduced

Swet-parser converts various interface document data into SWET metadata. Swet-parser uses metadata to customize front-end interface layer code, interface mock data, and model definitions.

The Swagger data source SWEt-Parser already provides a default adapter for converting sweT metadata

For data formats that are not yet supported, users can choose to provide their own adapters to convert sweT metadata

Quick start

  • 1, install,
$ npm i @ad/swet-parser -S
Copy the code
  • 2, use,

Swet-parser An example command output is www.baidu.com

// Export the parser module
import { Parser } from '@ad/swet-parser'

/** * Parameter 1: original data source, Swagger data source supports no additional adapter by default * Parameter 2: config configuration item, see configuration item */ for details
const parser = new Parser(originalData, config)

// Listen for error and warning events
parser
  .on('error'.(errorInfo) = > {

  })
  .on('warn'.(warnInfo) = >{})// Convert raw data to metadata and return metadata
const standardDataSource = parser.transformToStandard()

// Get all model definition data
const interfaces = parser.getInterfaceGenerators()

// Get all service definition data
const controllers = parser.getControllers()

// Get all mock data
const allMockData = parser.getAllMockData()

// Get the entry file data when the service is split by module
const serviceEntryCode = parser.getEntryCode()


Copy the code

API

parser = new Parser(originalData, config)

Create an instance of Parser with two parameters:

  • originalData: Record<string, any>: Original data source
  • config: Config: configuration items

on

Instance methods that listen for instance events and return the value that the instance itself can be chain-called

import { Parser, EventInfoCode } from '@ad/swet-parser'
// config Indicates the configuration item
import config from './config'
// The original data source
import originalData from './data'

const parser = new Parser(originalData, config)

// Listen for warnings and error events
parser
  .on(EventInfoCode.WARN, (warnInfo) = > {
    console.log(warnInfo.errorMsg)
  })
  .on(EventInfoCode.Error, () = > {
    console.log(errorInfo.errorMsg)
    process.exit(1)})Copy the code

transformToStandard

Instance method that converts raw data into metadata and returns metadata

import fs from 'fs-extra'
import path from 'path'

// Get the transformed metadata
const standardDataSource = parser.transformToStandard()

// Write metadata to a file
const standardJsonPath = path.join(__dirname, './standard.json')

fs.writeFileSync(
  standardJsonPath,
  JSON.stringify(this.standardJson, null.2))Copy the code

getInterfaceGenerators

Instance method that gets the model definition data generated from the incoming document

import fs from 'fs-extra'

const interfaceGenerators = this.parser.getInterfaceGenerators()

let code = ' '

for (const inter of interfaceGenerators) {
  // The definition of each model
  const interfaceItemCode = inter.toCode().content

  code += interfaceItemCode
}

// Write the model definition to a file
fs.writeFileSync(path.join(__dirname, 'models.d.ts'), code)


Copy the code

getControllers

Instance method to get the service data generated from the incoming document

const controllers = this.parser.getControllers()

// Service data for all modules
let code = ' '
// Record service data for each module
const controllersCode = Object.create(null)

for (const controllerName in controllers) {
  const services = controllers[controllerName]

  // Service data for each module
  let serviceCode = ' ' 

  // Use the controller module to generate the service
  for (const service of services) {

    if (supportTs) { // ts format serviceserviceCode += service.toCode()? .content.typescript ||' 'code += service.toCode()? .content.typescript ||' '
    } else { // The js format is serviceserviceCode += service.toCode()? .content.javascript ||' 'code += service.toCode()? .content.javascript ||' '
    }

  }
  controllersCode[controllerName] = serviceCode
}
Copy the code

getAllMockData

Instance method to get the mock data generated from the incoming document

import fs from 'fs-extra'
import path from 'path'

const allMockData = parser.getAllMockData()

for (const mockDataArr of Object.values(allMockData)) {
  for (const mockData of mockDataArr) {
    
    const { url, method, content } = mockData
    const finalUrl = path.join(config.baseUrl, url)
    let existData = undefined

    // Determine whether mock data already exists. Existing mock data is not overwritten
    if (fs.existsSync(path.join(finalUrl, `${mockData.method}.js`))) {
      const dataFunc = require(path.join(finalUrl, `${method}.js`))
      existData = isFunction(dataFunc) ? dataFunc() : dataFunc
    }

    mockResArr.push({
      method,
      content: content.toCode(existData),
      finalUrl,
      url,
    })
  }
}
Copy the code

getEntryCode

Instance method, file sharding case all service entry file data

// The service calls this method when it splits modules to generate data for the entry file
const serviceEntryCode = parser.getEntryCode()
Copy the code

Configuration items

baseUrl: string

Description: Optional, generate uniform URL prefix for service

requestHeaders: Record<string, string>

Description: Optional, add custom headers for service

prettierConfig: Record<string, any>

Description: Optional, prettier configuration item

forceOptional: boolean

Description: Optional. Whether to force the parameter is optional

level: number

Description: Optional, maximum level of references, default: 6

interfacePrefix: string

Description: Optional, generate interface name prefix, default: ‘I’

serviceFilter: (controllerName: string, operationId: string, path: string, method: string) => boolean

Description: Optional, customize whether to generate the service function

transformFunctionName: (controllerName: string, operationId: string, path: string, method: string) => boolean

Description: Optional, custom generated service name

apiTemplate: () => ({ leadingCode? : string; trailingCode? : string; returnKey? : string })

Description: Optional, mock data preprocessing, default:

apiTemplate: () = > {
  return {
    leadingCode: `import axios from 'axios'`.trailingCode: ' '.returnKey: 'data'}}Copy the code

adapter: AdapterConstructor

Optional, adapter to convert raw data, built-in Swagger data format adapter

abstract class Adapter {
  abstract transform(): StandardDataSource
}

interface AdapterConstructor {
  new (originalData: Record<string.any>): Adapter
}
Copy the code