項目介紹
papio-h5主要做的是對接口的統(tǒng)一管理。借助于typescript的裝飾器功能,使用起來更簡單。目前只適配于vue項目(目前項目處于初始的開發(fā)階段)。
1 地址
- 項目地址: https://github.com/potenstop/papio-h5
- 實戰(zhàn)的項目地址: https://github.com/potenstop/mis-front
2 安裝
npm install papio-h5
npm install axios # http請求框架
npm install typescript # 建議使用typescript3版本
papio-h5 內(nèi)部只有type-interface reflect-metadata agentkeepalive三個包的依賴,保持項目的清潔。
3 項目目錄結(jié)構(gòu)
- src
- assets # 資源文件
- bmo # 內(nèi)部使用的類
- common # 通用文件
- constant # 常量類
- util # 工具類
- components #
- config # 配置類
- dao # 數(shù)據(jù)獲取類
- api # http的方式的數(shù)據(jù)獲取類
- locale # 多語言定義類
- mock
- plugin
- request # 請求類
- response # 響應類
- router
- store
- views
4 快速使用
4.1新增 src/config/HttpApiConfiguration.ts
/**
*
* 功能描述:
*
* @className RestTestHttpConfiguration
* @projectName papio
* @author yanshaowen
* @date 2019/2/14 10:19
*/
import { IDataSource } from 'type-interface'
import { AxiosDataSource, Bean, Configuration, MapperScan } from 'papio-h5'
@Configuration
// 當前的配置作用的目錄
@MapperScan('/src/dao/api')
export class HttpApiConfiguration {
// bean對應的是每個資源的對象
@Bean
public HttpApiConfigurationMaster (): IDataSource {
const httpDataSource = new AxiosDataSource()
httpDataSource.setName('master')
httpDataSource.setReadOnly(false)
// 后端api的地址
httpDataSource.setUrl('http://api-gateway.potens.top')
httpDataSource.setCookieKeyList(['token'])
httpDataSource.build()
return httpDataSource
}
}
4.2 前端js中導入
src/App.vue
<script lang="ts">
...
import '@/config/HttpApiConfiguration'
...
</script>
4.3 定義接口
新增 src/dao/api/CmsApi.ts
/**
*
* 功能描述:
*
* @className UserApi
* @projectName web-front
* @author yanshaowen
* @date 2019/6/24 14:14
*/
import {
AxisoRemote, GetMapping, PostMapping, RequestBody,
RequestMapping,
RequestMethod,
RequestParam,
ReturnGenericsProperty
} from 'papio-h5'
// 后端返回的統(tǒng)一json的最上層 如{code: 1 , data: '', message: ''}
import { ApiResult } from '@/bmo/ApiResult'
import { UploadTopicListItemResponse } from '@/response/UploadTopicListItemResponse'
// 配置后端的地址 filepath對應到config中的MapperScan注解的值 timeout的時間是10秒
// 如這里請求地址前綴為http://api-gateway.potens.top/cms-api/
@AxisoRemote({ filepath: '/src/dao/api', name: 'cms-api', timeout: 10000 })
export class CmsApi {
// 定義的是get請求 URI=/mis/word/batch/course/topic
@GetMapping('/mis/word/batch/course/topic')
// 定義接口的返回值 @ReturnGenericsProperty對應json轉(zhuǎn)bean對象的規(guī)則
@ReturnGenericsProperty(ApiResult, new Map<string, new() => object>().set('data', Array).set('data.Array', UploadTopicListItemResponse))
// 定義入?yún)?@RequestParam為url傳參
public wordBatchCourseTopic (@RequestParam('filepath') filepath: string): Promise<ApiResult<UploadTopicListItemResponse[]>> {
return null
}
}
4.3 定義返回值
新增 src/bmo/ApiResult.ts
/**
*
* 功能描述:
*
* @className ApiResult
* @projectName web-front
* @author yanshaowen
* @date 2019/6/24 14:21
*/
import { JsonProperty } from 'papio-h5'
export class ApiResult<T> {
@JsonProperty
private code: string
@JsonProperty
private data: T
@JsonProperty
private message: string
constructor () {
this.code = '0'
this.message = 'suc'
}
public getCode (): string {
return this.code
}
public setCode (code: string): void {
this.code = code
}
public getData (): T {
return this.data
}
public setData (data: T): void {
this.data = data
}
public getMessage (): string {
return this.message
}
public setMessage (message: string): void {
this.message = message
}
}
新增src/response/UploadTopicListItemResponse.ts
import { JsonProperty, ReturnGenericsProperty } from 'papio-h5'
/**
*
* 功能描述:
*
* @className UploadTopicListItemResponse
* @projectName mis-front
* @author yanshaowen
* @date 2019/10/27 9:21
*/
export class UploadTopicListItemResponse {
@JsonProperty
private title: string
@JsonProperty
private topicType: number
@JsonProperty
@ReturnGenericsProperty(Array, new Map<string, {new(): object}>().set('Array', String))
private optionList: string[]
public getTitle (): string {
return this.title
}
public setTitle (title: string): void {
this.title = title
}
public getTopicType (): number {
return this.topicType
}
public setTopicType (topicType: number): void {
this.topicType = topicType
}
public getOptionList (): string[] {
return this.optionList
}
public setOptionList (optionList: string[]): void {
this.optionList = optionList
}
}
4.4 view中調(diào)用接口
新增 views/Test.vue
<template>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { CmsApi } from '@/dao/api/CmsApi'
const cmsApi = new CmsApi()
@Component
export default class Test extends Vue {
private async created () {
// result類型為ApiResult<UploadTopicListItemResponse>
const result = await cmsApi.wordBatchCourseTopic("abc")
}
}
4.5 總結(jié)
以上過程就可以完成后端的一個接口調(diào)用了。如果用axios直接調(diào)用的話相當于下面的代碼。
axios.get('http://api-gateway.potens.top/cms-api/mis/word/batch/course/topic?filepath=abc')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
雖然看上去定義了很多類,但是提高了可讀性和靈活性,從定義上明顯就能知道接口的請求的參數(shù)和響應參數(shù)的定義。其實就是讓前端也使用起強類型,減少維護的成本。