parent
4610001721
commit
f28d8c283a
@ -0,0 +1,92 @@ |
||||
//服务端地址
|
||||
|
||||
const server="http://localhost:8080" |
||||
|
||||
const prefix={ |
||||
user:"/api/user" |
||||
} |
||||
//服务器接口地址
|
||||
export const API={ |
||||
account:{ |
||||
register:prefix.user+"/register" |
||||
} |
||||
} |
||||
|
||||
export enum Method { |
||||
PUT="PUT", |
||||
POST="POST", |
||||
GET="GET" |
||||
} |
||||
|
||||
export enum Result { |
||||
OK, |
||||
FAIL |
||||
} |
||||
|
||||
|
||||
/** |
||||
* 响应数据 |
||||
*/ |
||||
export abstract 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},transformFun:Function,callback:Function) { |
||||
let formData=new FormData() |
||||
for(let formParam in formParams){ |
||||
formData.append(formParam,formParams[formParam]) |
||||
} |
||||
fetch(server+api,{ |
||||
method:Method.PUT, |
||||
body:formData |
||||
}) |
||||
.then( |
||||
response=>{if(response.status===200){ |
||||
return response.json() |
||||
}else{ |
||||
throw new Error("遇到无法处理的错误,请联系管理员") |
||||
|
||||
}} |
||||
) |
||||
.catch( |
||||
error =>console.error('Error:', error) |
||||
) |
||||
.then((response:JSONResponse<Q>)=>{ |
||||
let transform:T=transformFun() |
||||
callback(transform.transform(response)) |
||||
}) |
||||
} |
@ -0,0 +1,26 @@ |
||||
/** |
||||
* 返回信息 |
||||
*/ |
||||
import {JSONResponse, TransformData} from "./interface"; |
||||
|
||||
export enum RegisterMessage { |
||||
//注册成功
|
||||
ok = "ok", |
||||
//系统异常,注册失败
|
||||
fail = "fail", |
||||
//用户id重复
|
||||
user_repeat = "user_repeat", |
||||
//表单解析错误
|
||||
form_parse_error = "form_parse_error" |
||||
} |
||||
|
||||
class RegisterRes implements JSONResponse<RegisterMessage> { |
||||
|
||||
} |
||||
|
||||
export class RegisterTransform extends TransformData<RegisterMessage, RegisterRes> { |
||||
protected newObject(): RegisterRes { |
||||
return new RegisterRes(); |
||||
} |
||||
|
||||
} |
Loading…
Reference in new issue