import Context from '../context' ; /** 公共请求函数 */ export async function Fetch ( ctx , input , init , timeout ? ) { if ( ctx . user . data . token ) { const requestHeaders = new Headers ( ) ; requestHeaders . set ( 'Authorization' , `Bearer ${ ctx . user . data . token }` ) ; init . headers = requestHeaders ; } try { let resp ; if ( ( typeof timeout !== 'number' && ctx . conf . reqTimeout === 0 ) || timeout === 0 ) { resp = await fetch ( input , init ) ; } else { resp = await timeoutPromise ( timeout || ctx . conf . reqTimeout || 15000 , fetch ( input , init ) ) ; } if ( ! resp . ok && resp . status !== 401 ) throw new Error ( `请求响应 ${ resp . status }` ) ; let json = await resp . json ( ) ; const recall = ( resolve , reject ) => { Fetch ( ctx , input , init ) . then ( d => { resolve ( d ) ; } ) . catch ( err => { reject ( err ) ; } ) ; } ; if ( json . data && json . data . need_captcha ) { json = await ( new Promise < any > ( ( resolve , reject ) => { ctx . trigger ( 'checker-captcha' , { imgData : json . data . img_data , onSuccess : ( ) => { recall ( resolve , reject ) ; } , onCancel : ( ) => { reject ( json ) ; } } ) ; } ) ) ; } else if ( ( json . data && json . data . need_login ) || resp . status === 401 ) { json = await ( new Promise < any > ( ( resolve , reject ) => { ctx . trigger ( 'checker-admin' , { onSuccess : ( ) => { recall ( resolve , reject ) ; } , onCancel : ( ) => { reject ( json ) ; } } ) ; } ) ) ; } if ( ! json . success ) throw json ; return json ; } catch ( err ) { console . error ( err ) ; if ( err instanceof TypeError ) throw new Error ( `网络错误` ) ; throw err ; } } /** 公共 POST 请求 */ export async function POST < T > ( ctx , url , data ? ) { const init = { method : 'POST' , } ; if ( data ) init . body = ToFormData ( data ) ; const json = await Fetch ( ctx , url , init ) ; return ( ( json . data || { } ) as T ) ; } /** 公共 GET 请求 */ export async function GET < T > ( ctx , url , data ? ) { const json = await Fetch ( ctx , url + ( data ? ( `?${ new URLSearchParams ( data ) }` ) : '' ) , { method : 'GET' , } ) ; return ( ( json . data || { } ) as T ) ; } /** 对象转 FormData */ export function ToFormData ( object ) { const formData = new FormData ( ) ; Object . keys ( object ) . forEach ( key => formData . append ( key , String ( object [ key ] ) ) ) ; return formData ; } /** 我靠，fetch 一个 timeout，都要丑陋的实现 */ function timeoutPromise < T > ( ms , promise ) { return new Promise ( ( resolve , reject ) => { const timeoutId = setTimeout ( ( ) => { reject ( new Error ( "请求超时" ) ) ; } , ms ) ; promise . then ( ( res ) => { clearTimeout ( timeoutId ) ; resolve ( res ) ; } , ( err ) => { clearTimeout ( timeoutId ) ; reject ( err ) ; } ) ; } ) ; }