py-uni
Version:
py-uni
68 lines (62 loc) • 2.25 kB
text/typescript
import {ErrorResponse} from "../domain/error-handle";
class Request {
interceptor: { request: null; response: null };
get: any;
post: any;
constructor() {
this.interceptor = {
// 请求前的拦截
request: null,
// 请求后的拦截
response: null
}
// get请求
this.get = (url: string, data = {}, header = {}) => {
return this.request({
method: 'GET',
url,
header,
data
})
}
// post请求
this.post = (url: string, data = {}, header = {'content-type': 'application/x-www-form-urlencoded'}) => {
return this.request({
url,
method: 'POST',
header,
data
})
}
}
request(options: any = {}) {
return new Promise((resolve, reject) => {
options.complete = (response: any) => {
if (response.statusCode == 200) {
if (this.interceptor.response && typeof this.interceptor.response === 'function') {
// @ts-ignore
let resInterceptors = this.interceptor.response(response.data);
if (resInterceptors !== false) {
resolve(resInterceptors);
} else {
reject(response.data);
}
} else {
if (typeof response.data === 'object' && (response.data as any).error_response) {
response = new ErrorResponse(response.data as any);
}
if (response instanceof ErrorResponse) {
reject(response.errorResponse);
} else {
resolve(response.data);
}
}
} else {
reject(response)
}
}
uni.request(options);
})
}
}
export default new Request