moyan-api 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.eslintrc.js +28 -0
  2. package/.gitee/ISSUE_TEMPLATE.zh-CN.md +13 -0
  3. package/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +11 -0
  4. package/.prettierrc +5 -0
  5. package/CHANGELOG.md +5 -0
  6. package/LICENSE +201 -0
  7. package/README.en.md +36 -0
  8. package/README.md +153 -0
  9. package/dist/apiv2/axios.d.ts +13 -0
  10. package/dist/apiv2/axios.js +69 -0
  11. package/dist/apiv2/axios.js.map +1 -0
  12. package/dist/apiv2/base.d.ts +43 -0
  13. package/dist/apiv2/base.js +93 -0
  14. package/dist/apiv2/base.js.map +1 -0
  15. package/dist/apiv2/config.d.ts +1 -0
  16. package/dist/apiv2/config.js +26 -0
  17. package/dist/apiv2/config.js.map +1 -0
  18. package/dist/index.d.ts +4 -0
  19. package/dist/index.js +18 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/lib/axios.d.ts +13 -0
  22. package/dist/lib/axios.js +71 -0
  23. package/dist/lib/axios.js.map +1 -0
  24. package/dist/lib/base.d.ts +48 -0
  25. package/dist/lib/base.js +95 -0
  26. package/dist/lib/base.js.map +1 -0
  27. package/dist/lib/config.d.ts +1 -0
  28. package/dist/lib/config.js +26 -0
  29. package/dist/lib/config.js.map +1 -0
  30. package/dist/main.d.ts +15 -0
  31. package/dist/main.js +75 -0
  32. package/dist/main.js.map +1 -0
  33. package/dist/template/api.d.ts +16 -0
  34. package/dist/template/api.js +90 -0
  35. package/dist/template/api.js.map +1 -0
  36. package/dist/template/schemas.d.ts +13 -0
  37. package/dist/template/schemas.js +89 -0
  38. package/dist/template/schemas.js.map +1 -0
  39. package/dist/tsconfig.tsbuildinfo +1 -0
  40. package/dist/utils/mo.d.ts +28 -0
  41. package/dist/utils/mo.js +254 -0
  42. package/dist/utils/mo.js.map +1 -0
  43. package/package.json +38 -0
  44. package/src/index.ts +38 -0
  45. package/src/lib/base.ts +180 -0
  46. package/src/main.ts +90 -0
  47. package/src/template/api.ts +102 -0
  48. package/src/template/schemas.ts +89 -0
  49. package/src/utils/mo.ts +402 -0
  50. package/tsconfig.json +20 -0
  51. package/view/api.ejs +25 -0
  52. package/view/schemas.ejs +12 -0
@@ -0,0 +1,180 @@
1
+
2
+ export type MoMethod = 'POST' | 'GET' | 'DELETE' | 'PUT'
3
+ export interface ObjectAny {
4
+ [key: string]: any //一般用于字段字段
5
+ }
6
+
7
+ export interface Option {
8
+ /**
9
+ * 下载文件的文件名
10
+ */
11
+ fileName?: string
12
+ /**
13
+ * 是否使用 api的prefix;
14
+ * @default true
15
+ */
16
+ prefix?: boolean
17
+
18
+ /**
19
+ * 提示成功信息
20
+ * @default true
21
+ */
22
+ hintSuccess?: boolean
23
+
24
+ /**
25
+ * 提示错误信息
26
+ * @default true
27
+ */
28
+ hintFail?: boolean
29
+
30
+ /**
31
+ * 是否显示加载蒙版
32
+ * @default false
33
+ */
34
+ showLoading?: boolean
35
+
36
+ /**
37
+ * 成功提示消息,successMsg可以为string和Function,Function返回提示语, 如果没有定义了改属性,则默认使用api接口返回的message
38
+ * @default null
39
+ */
40
+ successMsg?: ((res: any) => string) | string | null
41
+
42
+ /**
43
+ * 失败提示消息,failMsg可以为string和Function,Function返回提示语,如果没有定义了改属性,则默认使用api接口返回的message
44
+ * @default null
45
+ */
46
+ failMsg?: ((err: any) => string) | string | null
47
+
48
+ /**
49
+ * 加载状态
50
+ */
51
+ loading?: boolean
52
+ }
53
+
54
+
55
+ export interface ApiCallProps<T> {
56
+ params?: T
57
+ option?: Option | {}
58
+ }
59
+
60
+ export abstract class RequestClass {
61
+ abstract request(apiEntity:ApiEntity):Promise<any>
62
+ }
63
+
64
+ export interface SubApiEntity extends RequestClass{}
65
+
66
+
67
+ export abstract class ApiCall<ReqType, ResType> extends Promise<ResType & ObjectAny> {
68
+ static MoCall:SubApiEntity
69
+
70
+ static use (moCall: SubApiEntity ){
71
+ ApiCall.MoCall = moCall
72
+ }
73
+
74
+ static hasPrompted = false
75
+
76
+ params!: ReqType | { [key: string]: any }
77
+ result!: ResType & ObjectAny
78
+
79
+ option!: Option
80
+
81
+ static hintSuccessHandler = (result: any) => {}
82
+
83
+ static hintFailHandler = (err: any) => {}
84
+
85
+ /**
86
+ * 请求路径
87
+ */
88
+ abstract path: string
89
+
90
+ abstract method: MoMethod
91
+
92
+ error: any
93
+
94
+ response: any
95
+
96
+ resolve!: (result: ApiCall<ReqType, ResType>['result']) => void
97
+ reject!: (err: any) => void
98
+
99
+ get successMsg() {
100
+ if (typeof this.option.successMsg === 'string') {
101
+ return this.option.successMsg
102
+ } else if (typeof this.option.successMsg === 'function') {
103
+ return this.option.successMsg(this.result)
104
+ } else if (this.result.message) {
105
+ return this.result.message
106
+ }
107
+ return '请求成功'
108
+ }
109
+
110
+ get failMsg() {
111
+ if (this.error) {
112
+ if (typeof this.option.failMsg === 'string') {
113
+ return this.option.failMsg
114
+ } else if (typeof this.option.failMsg === 'function') {
115
+ return this.option.failMsg(this.error)
116
+ }
117
+ return this.error.message || this.error.data ? this.error.data.mssage : '请求错误'
118
+ }
119
+ return false
120
+ }
121
+
122
+ constructor(props?: ApiCallProps<ReqType>) {
123
+ if (typeof props === 'function') {
124
+ super(props)
125
+ } else {
126
+ const slef: any = {}
127
+ super((resolve, reject) => {
128
+ slef.resolve = resolve
129
+ slef.reject = reject
130
+ })
131
+ Object.assign(this, slef)
132
+ setTimeout(() => {
133
+ this.init(props)
134
+ this.exec()
135
+ })
136
+ }
137
+ }
138
+
139
+ init(props?: ApiCallProps<ReqType>) {
140
+ const defaultOption: Option = {
141
+ prefix: true,
142
+ hintSuccess: false,
143
+ hintFail: true,
144
+ showLoading: true,
145
+ loading: false,
146
+ successMsg: (res) => {
147
+ return res.message || '请求成功'
148
+ },
149
+ failMsg: (err) => {
150
+ return err.message
151
+ }
152
+ }
153
+
154
+ this.option = this.option || {}
155
+ if (props && typeof props.option === 'object') {
156
+ const option = Object.assign(defaultOption, this.option, props.option)
157
+ Object.assign(props.option, option)
158
+ this.option = props.option
159
+ } else {
160
+ this.option = Object.assign(defaultOption, this.option)
161
+ }
162
+ this.params = props && props.params ? props.params : {}
163
+ }
164
+
165
+ exec() {
166
+ ApiCall.MoCall.request(this)
167
+ .then((response) => {
168
+ this.result = response.data
169
+ this.option.hintSuccess && !ApiCall.hasPrompted && ApiCall.hintSuccessHandler(this)
170
+ this.resolve(response.data)
171
+ })
172
+ .catch((err) => {
173
+ this.error = err
174
+ this.option.hintSuccess && !ApiCall.hasPrompted && ApiCall.hintFailHandler(this)
175
+ this.reject(err)
176
+ })
177
+ }
178
+ }
179
+
180
+ export interface ApiEntity extends ApiCall<any, any> {}
package/src/main.ts ADDED
@@ -0,0 +1,90 @@
1
+
2
+ import * as path from "path"
3
+ import MFManage, { mFconfig, smfType, SchemaManager } from "moyan-file-model"
4
+ import axios from 'axios'
5
+
6
+
7
+ import { ApiTemplate } from "./template/api"
8
+ import { SchemasTemplate } from "./template/schemas"
9
+
10
+ export class ApisdkCreator {
11
+ mFManage: MFManage
12
+ error: Array<any> = []
13
+
14
+ get runPath() {
15
+ const g = process.env.INIT_CWD
16
+ return g
17
+ }
18
+
19
+ get packageData(){
20
+ return require(path.resolve('package.json'))
21
+ }
22
+
23
+ get outputPath(){
24
+ return path.resolve(this.packageData['moyan-api'] && this.packageData['moyan-api']['output']? this.packageData['moyan-api']['output']:"./src")
25
+ }
26
+
27
+ get openAPIObject(){
28
+ const file = this.packageData['moyan-api'] && this.packageData['moyan-api']['apijson']?this.packageData['moyan-api']['apijson']:'moyan.api.json'
29
+ console.info('获取本地数据:'+file)
30
+ const data = require(path.resolve(file))
31
+ return data
32
+ }
33
+
34
+ constructor() {
35
+ mFconfig.modulesPath = this.outputPath
36
+ mFconfig.modulesTemplatePath = path.resolve(__dirname, './')
37
+ mFconfig.modulesTemplateViewsName = path.resolve(__dirname,"../view")
38
+ }
39
+
40
+ schemaManagerData = {}
41
+
42
+ schemaManager: SchemaManager
43
+
44
+
45
+ async getRemoteData(){
46
+ const result = await axios.get(this.packageData['moyan-api']['jsonurl'])
47
+ return result.data
48
+ }
49
+
50
+ async init() {
51
+ let openAPIObject :any= {}
52
+ if(this.packageData['moyan-api'] && this.packageData['moyan-api']['jsonurl']){
53
+ console.log('获取远程数据:'+this.packageData['moyan-api']['jsonurl'])
54
+ openAPIObject = await this.getRemoteData()
55
+ }else{
56
+ openAPIObject = this.openAPIObject
57
+ }
58
+
59
+ if(!openAPIObject.openapi){
60
+ throw new Error('api 数据错误')
61
+ }
62
+
63
+ this.schemaManagerData = {
64
+ type: smfType.dir,
65
+ name: "api",
66
+ children: [
67
+ {
68
+ type: smfType.ts,
69
+ name: "index",
70
+ template: new ApiTemplate(openAPIObject)
71
+ },
72
+ {
73
+ type: smfType.ts,
74
+ name: "schemas",
75
+ template: new SchemasTemplate(openAPIObject)
76
+ }
77
+ ]
78
+ }
79
+ }
80
+
81
+ async create() {
82
+ await this.init()
83
+ this.mFManage = new MFManage()
84
+ this.schemaManager = new SchemaManager(this.schemaManagerData)
85
+ this.mFManage.run(this.schemaManager)
86
+ return this.error
87
+ }
88
+ }
89
+
90
+
@@ -0,0 +1,102 @@
1
+ import { OpenAPIObject } from '@nestjs/swagger'
2
+ import { Temp, Template, smfType } from 'moyan-file-model'
3
+
4
+ export class ApiTemplate extends Temp implements Template {
5
+ openAPIObject: OpenAPIObject
6
+
7
+ list: Array<any> = []
8
+
9
+ schemaKeys = []
10
+
11
+ constructor(openAPIObject:OpenAPIObject) {
12
+ super(smfType.ts)
13
+ this.openAPIObject = openAPIObject
14
+ this.init()
15
+ }
16
+
17
+ init() {
18
+ const paths = new Map()
19
+ for (const key in this.openAPIObject.paths) {
20
+ for (const key1 in this.openAPIObject.paths[key]) {
21
+ const item = this.openAPIObject.paths[key][key1]
22
+ item.path = key
23
+ item.method = key1.toUpperCase()
24
+ paths.set(`${item.operationId}`, {
25
+ ...item,
26
+ reqType: this._getReqType(item),
27
+ resType: this._getResType(item),
28
+ reqDescription: this._getReqDescription(item),
29
+ resDescription: this._getResDescription(item),
30
+ tag: JSON.stringify(item.tag)
31
+ })
32
+ }
33
+ }
34
+ this.list = [...paths.values()]
35
+ this.schemaKeys = Object.keys(this.openAPIObject.components.schemas)
36
+ }
37
+
38
+ private _getReqType(item: any) {
39
+ try {
40
+ return this.getSchemaEntity(item.requestBody.content['application/json'].schema.$ref)
41
+ } catch {
42
+ return this.parseSchema(item)
43
+ }
44
+ }
45
+
46
+ parseSchema(schema: any) {
47
+ const parameters = new Map()
48
+
49
+ schema.parameters.forEach((item: any) => {
50
+ parameters.set(item.name, item)
51
+ })
52
+ const arr = [...parameters.values()]
53
+
54
+ try {
55
+ let str = '{'
56
+ arr.forEach((item1: any) => {
57
+ str += ` ${item1.name}${item1.required ? '' : '?'}:${item1.schema.type},${item1.description ? ' //' + item1.description : ''}\n`
58
+ })
59
+ str += '}'
60
+ return str
61
+ } catch (e) {
62
+ return `any`
63
+ }
64
+ }
65
+
66
+ getSchemaEntity(str: string): string {
67
+ const arr = str.split('/')
68
+ return arr[3] || `any`
69
+ }
70
+
71
+ _getResType(item: any) {
72
+ try {
73
+ return this.getSchemaEntity(item.responses[200].content['application/json'].schema.$ref)
74
+ } catch {
75
+ return `any`
76
+ }
77
+ }
78
+
79
+ _getReqDescription(item: any) {
80
+ try {
81
+ return item.requestBody.description || ''
82
+ } catch {
83
+ return ''
84
+ }
85
+ }
86
+
87
+ _getResDescription(item: any) {
88
+ try {
89
+ return item.responses[200].description || ''
90
+ } catch {
91
+ return ''
92
+ }
93
+ }
94
+
95
+ public async run() {
96
+ try {
97
+ return await this.render('api')
98
+ } catch (err) {
99
+ console.info('===========ApiTemplate=err==========', err)
100
+ }
101
+ }
102
+ }
@@ -0,0 +1,89 @@
1
+ import { OpenAPIObject } from '@nestjs/swagger'
2
+ import { Temp, Template, smfType } from 'moyan-file-model'
3
+
4
+ export class SchemasTemplate extends Temp implements Template {
5
+ openAPIObject: OpenAPIObject
6
+
7
+ list: Array<any> = []
8
+
9
+ constructor(openAPIObject:OpenAPIObject) {
10
+ super(smfType.ts)
11
+ this.openAPIObject = openAPIObject
12
+ this.init()
13
+ }
14
+
15
+ init() {
16
+ const schemas = new Map()
17
+ for (const key in this.openAPIObject.components.schemas) {
18
+ const arr = this.parseSchema(this.openAPIObject.components.schemas[key])
19
+ schemas.set(key, {
20
+ key,
21
+ arr
22
+ })
23
+ }
24
+ this.list = [...schemas.values()]
25
+ }
26
+
27
+ parseSchema(schema: any) {
28
+ const parameters = new Map()
29
+ for (const key in schema.properties) {
30
+ const item = schema.properties[key]
31
+
32
+ if (item.type && item.type === 'array') {
33
+ if (item.items && item.items.$ref) {
34
+ parameters.set(key, `${key}${this.isRequired(schema, key) ? '?' : ''}:Array<${this.getSchemaEntity(item.items.$ref)}>${this.getDescription(item)}`)
35
+ continue
36
+ } else if (item.items && item.items.oneOf && Array.isArray(item.items.oneOf)) {
37
+ const schemaEntityArr = item.items.oneOf.map((item1: any) => {
38
+ return this.getSchemaEntity(item1.$ref)
39
+ })
40
+ parameters.set(key, `${key}${this.isRequired(schema, key) ? '?' : ''}:Array<${schemaEntityArr.join('|')}>${this.getDescription(item)}`)
41
+ continue
42
+ } else {
43
+ parameters.set(key, `${key}${this.isRequired(schema, key) ? '?' : ''}:Array<any>${this.getDescription(item)}`)
44
+ continue
45
+ }
46
+ } else if (Array.isArray(item.allOf)) {
47
+ const schemaEntityArr = item.allOf.map((item1: any) => {
48
+ return this.getSchemaEntity(item1.$ref)
49
+ })
50
+ parameters.set(key, `${key}${this.isRequired(schema, key) ? '?' : ''}:${schemaEntityArr.join('|')}${this.getDescription(item)}`)
51
+ continue
52
+ } else if (Array.isArray(item.oneOf)) {
53
+ const schemaEntityArr = item.oneOf.map((item1: any) => {
54
+ return this.getSchemaEntity(item1.$ref)
55
+ })
56
+ parameters.set(key, `${key}${this.isRequired(schema, key) ? '?' : ''}:${schemaEntityArr.join('|')}${this.getDescription(item)}`)
57
+ continue
58
+ } else if (item.type) {
59
+ parameters.set(key, `${key}${this.isRequired(schema, key) ? '?' : ''}:${item.type}${this.getDescription(item)}`)
60
+ continue
61
+ } else {
62
+ parameters.set(key, `${key}${this.isRequired(schema, key) ? '?' : ''}:any${this.getDescription(item)}`)
63
+ continue
64
+ }
65
+ }
66
+ return [...parameters.values()].map((item) => item + '\n')
67
+ }
68
+
69
+ isRequired(schema: any, key: string) {
70
+ return !(schema.required && schema.required.includes(key))
71
+ }
72
+
73
+ getSchemaEntity(str: string): string {
74
+ const arr = str.split('/')
75
+ return arr[3] || `any`
76
+ }
77
+
78
+ getDescription(item: any) {
79
+ return item.description ? ' // ' + item.description : ''
80
+ }
81
+
82
+ public async run() {
83
+ try {
84
+ return await this.render('schemas')
85
+ } catch (err) {
86
+ console.info('===========SchemasTemplate=err==========', err)
87
+ }
88
+ }
89
+ }