import { login } from "./login" ; import { SESSION_KEY , LOGIN_FAIL_CODES } from "../../config/global-config" ; import wxp from "../wxp" ; import { ICgiConfig , getHost } from "../../config/cgi-config" ; import { getLogger } from "../log" ; import { IRequestOption } from "../../api/common" ; import { reLaunch } from "../navigate" ; const logger = getLogger ( "request" ) ; const TRY_LOGIN_LIMIT = 1 ; const TRY_RETRY_LIMIT = 3 ; export async function request ( cgiConfig , data = { } , options = { } ) { logger . RUN ( "request invoke, " , { cgiConfig , data , options } ) ; if ( cgiConfig . url != "/login" ) { await login ( ) ; } let session = wx . getStorageSync ( SESSION_KEY ) ; let tryLoginCount = options . tryLoginCount || 0 ; const dataWithSession = { ... data , [ SESSION_KEY ] : session } ; const requestOption = { url : getHost ( ) + cgiConfig . url , method : cgiConfig . method , data : dataWithSession , header : { "content-type" : cgiConfig . contentType || "application/json" } } ; logger . RUN ( "before wx.request, " , { requestOption } ) ; if ( options . showLoading ) { wx . showLoading ( { title : options . loadingText || "加载中" } ) ; } const res = await wxp . request ( requestOption ) ; logger . RUN ( "after wx.request" ) ; if ( options . showLoading ) { wx . hideLoading ( ) ; } if ( res . statusCode === 200 ) { const data = res . data ; if ( LOGIN_FAIL_CODES . indexOf ( data . return_code ) > - 1 && tryLoginCount <= TRY_LOGIN_LIMIT ) { wx . removeStorageSync ( SESSION_KEY ) ; options . tryLoginCount = ++ tryLoginCount ; return request ( cgiConfig , data , options ) ; } else if ( data . ret_code == 0 ) { return Promise . resolve ( data ) ; } else { if ( options . showNetworkRetry ) { reLaunch ( "/pages/result/result" , { urlParams : { type : "warn" , title : "页面异常" , info : "系统繁忙，请稍后再试" } } ) ; } else if ( options . showErrorToast ) { wx . showToast ( { title : options . errorText || "系统繁忙，请稍后再试" } ) ; } return Promise . reject ( data . return_code ) ; } } else { if ( options . showNetworkRetry ) { if ( options . tryRetryCount && options . tryRetryCount < TRY_RETRY_LIMIT ) { const res = await wxp . showModal ( { title : options . networkRetryText || "网络异常，请稍后再试" , showCancel : false , confirmText : "点击重试" } ) ; if ( res . confirm ) { return await request ( cgiConfig , data , { ... options , tryRetryCount : options . tryRetryCount ? options . tryRetryCount + 1 : 1 } ) ; } } else { reLaunch ( "/pages/result/result" , { urlParams : { type : "warn" , title : "网络异常" , info : "系统繁忙，请稍后再试" } } ) ; } } else if ( options . showErrorToast ) { wx . showToast ( { title : options . errorText || "系统繁忙，请稍后再试" } ) ; } return Promise . reject ( res . statusCode ) ; } }