You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
99 lines
2.2 KiB
99 lines
2.2 KiB
//服务端地址
|
|
|
|
|
|
import {server} from "./api";
|
|
|
|
export enum Method {
|
|
PUT="PUT",
|
|
POST="POST",
|
|
GET="GET"
|
|
}
|
|
|
|
export enum Result {
|
|
OK="OK",
|
|
FAIL="FAIL"
|
|
}
|
|
|
|
|
|
/**
|
|
* 响应数据
|
|
*/
|
|
export class JSONResponse<Q> {
|
|
result?:Result
|
|
customResult?:Q
|
|
}
|
|
|
|
/**
|
|
* 数据类型转换
|
|
*/
|
|
export abstract class TransformData<Q,T extends JSONResponse<Q>> {
|
|
protected target: T
|
|
|
|
constructor() {
|
|
this.target = this.newObject();
|
|
}
|
|
|
|
protected abstract newObject(): T
|
|
|
|
public transform(data:any){
|
|
this.transformResult(data)
|
|
this.transformBody(data)
|
|
return this.target
|
|
}
|
|
|
|
protected transformBody(data:any){
|
|
|
|
}
|
|
|
|
private transformResult(data:any){
|
|
if("result" in data ) {
|
|
this.target.result = data.result
|
|
}
|
|
if("customResult" in data){
|
|
this.target.customResult = data.customResult
|
|
}
|
|
}
|
|
}
|
|
|
|
//发送请求
|
|
export function request<Q,E extends JSONResponse<Q>,T extends TransformData<Q,E>>(api:string,method:Method,formParams: {[propName:string]: string | Blob|Array<string>},transform:T,callback:Function) {
|
|
let formData
|
|
if(method===Method.GET) {
|
|
formData=null
|
|
}else{
|
|
formData=new FormData()
|
|
for (let formParam in formParams) {
|
|
let params= formParams[formParam]
|
|
if(params instanceof Array){
|
|
for(let value in params){
|
|
if(params.hasOwnProperty(value)) {
|
|
formData.append(formParam + '[]', params[value])
|
|
}
|
|
}
|
|
}else if(params instanceof Blob||typeof params==="string"){
|
|
formData.append(formParam,params)
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
fetch(server+api,{
|
|
method:method,
|
|
body:formData,
|
|
credentials: 'include',
|
|
})
|
|
.then(
|
|
response=>{if(response.status===200){
|
|
return response.json()
|
|
}else{
|
|
throw new Error("遇到无法处理的错误,请联系管理员")
|
|
|
|
}}
|
|
)
|
|
.catch(
|
|
error =>console.error('Error:', error)
|
|
)
|
|
.then((response:JSONResponse<Q>)=>{
|
|
callback(transform.transform(response))
|
|
})
|
|
}
|
|
|