Browse Source

更新 'src/services/net.service.ts'

Caner 2 years ago
parent
commit
b68f169dea
1 changed files with 97 additions and 160 deletions
  1. 97 160
      src/services/net.service.ts

+ 97 - 160
src/services/net.service.ts

@@ -20,85 +20,25 @@ export default class NetService extends Service {
    * @param url 接口地址
    * @param url 接口地址
    * @param params 接口参数
    * @param params 接口参数
    */
    */
-  post(url: string, params: any = {}, timeout = 6000): Promise<NetResult> {
-    const newToken = `${storeService.tokenInfo.type} ${storeService.tokenInfo.access_token}`
-    return new Promise((resolve) => {
-      const controller = new AbortController()
-      const { signal } = controller
-      setTimeout(() => {
-        controller.abort()
-      }, timeout)
-      fetch(urls + url, {
-        signal,
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-          Authorization: newToken
-        },
-        body: JSON.stringify(params)
-      }).then((res) => res.json()).then((res) => {
-        if (res.code !== 200) {
-          this.throw(res.msg, import.meta.url, 404)
-        }
-        resolve({
-          success: res?.success,
-          data: res?.data || null,
-          msg: res?.msg || null,
-          code: res?.code || -1
-        })
-      }).catch((err: any) => {
-        resolve({
-          success: false,
-          data: null,
-          msg: `接口 [${url}] 错误: ${err.message || err}`,
-          code: -1
-        })
-      })
-    })
+  post(url: string, params: Any = {}, timeout = 6000): Promise<NetResult> {
+    return this.fetch('/api' + url, { method: 'POST', body: JSON.stringify(params) }, timeout)
+  }
+
+  /**
+   * upload上传文件接口
+   * @param url 接口地址
+   * @param params 接口参数
+   */
+  upload(url: string, params: Any, timeout = 0): Promise<NetResult> {
+    return this.fetch('/api' + url, { method: 'POST', headers: { Authorization: this.tokenService.token }, body: params }, timeout)
   }
   }
 
 
   /**
   /**
    * get请求api接口
    * get请求api接口
    * @param url 接口地址
    * @param url 接口地址
    */
    */
-  get(url: string, params: any = {}, timeout = 6000): Promise<NetResult> {
-    let urlParams = ''
-    const newToken = `${storeService.tokenInfo.type} ${storeService.tokenInfo.access_token}`
-    for (const key in params) {
-      if (params[key]) {
-        urlParams += (urlParams.includes('?') ? '&' : '?')
-        urlParams += `${key}=${params[key]}`
-      }
-    }
-    return new Promise((resolve) => {
-      const controller = new AbortController()
-      const { signal } = controller
-      setTimeout(() => {
-        controller.abort()
-      }, timeout)
-      fetch(urls + url + urlParams, {
-        signal,
-        method: 'get',
-        headers: {
-          'Content-Type': 'application/json',
-          Authorization: newToken
-        }
-      }).then((res) => res.json()).then((res) => {
-        resolve({
-          success: res?.success,
-          data: res?.data || null,
-          msg: res?.msg || null,
-          code: res?.code || -1
-        })
-      }).catch((err: any) => {
-        resolve({
-          success: false,
-          data: null,
-          msg: `接口 [${url.split('?')[0]}] 错误: ${err?.message || err}`,
-          code: -1
-        })
-      })
-    })
+  get(url: string, timeout = 6000): Promise<NetResult> {
+    return this.fetch('/api' + url, { method: 'get' }, timeout)
   }
   }
 
 
   /**
   /**
@@ -106,36 +46,7 @@ export default class NetService extends Service {
    * @param url 接口地址
    * @param url 接口地址
    */
    */
   del(url: string, timeout = 6000): Promise<NetResult> {
   del(url: string, timeout = 6000): Promise<NetResult> {
-    const newToken = `${storeService.tokenInfo.type} ${storeService.tokenInfo.access_token}`
-    return new Promise((resolve) => {
-      const controller = new AbortController()
-      const { signal } = controller
-      setTimeout(() => {
-        controller.abort()
-      }, timeout)
-      fetch(urls + url, {
-        signal,
-        method: 'DELETE',
-        headers: {
-          'Content-Type': 'application/json',
-          Authorization: newToken
-        }
-      }).then((res) => res.json()).then((res) => {
-        resolve({
-          success: res?.success,
-          data: res?.data || null,
-          msg: res?.msg || null,
-          code: res?.code || -1
-        })
-      }).catch((err: any) => {
-        resolve({
-          success: false,
-          data: null,
-          msg: `接口 [${url.split('?')[0]}] 错误: ${err?.message || err}`,
-          code: -1
-        })
-      })
-    })
+    return this.fetch('/api' + url, { method: 'DELETE' }, timeout)
   }
   }
 
 
   /**
   /**
@@ -143,85 +54,111 @@ export default class NetService extends Service {
    * @param url 接口地址
    * @param url 接口地址
    * @param params 接口参数
    * @param params 接口参数
    */
    */
-  put(url: string, params: any = {}, timeout = 6000): Promise<NetResult> {
-    const newToken = `${storeService.tokenInfo.type} ${storeService.tokenInfo.access_token}`
+  put(url: string, params: Any = {}, timeout = 6000): Promise<NetResult> {
+    return this.fetch('/api' + url, { method: 'put', body: JSON.stringify(params) }, timeout)
+  }
+
+  /**
+   * 获取唯一序列ID
+   * @param type 类型
+   */
+  async fetchId(type: IDTypes) {
+    // const { success, data } = await this.get('/form/v3/source/id/' + type)
+    const { success, data } = await this.get('/form/v3/source/table/id/' + type)
+    if (success && data) {
+      return data as string
+    }
+    return null
+  }
+
+  /** token 续期 */
+  async refresh() {
+    this.put('/upms/v3/auth/check_token').catch(e => { })
+  }
+
+  /**
+   * 表单api接口
+   * @param url 接口地址
+   */
+  dataForm(options: { method: string, url: string, headers: { [key: string]: Any }, params: { [key: string]: Any } }, timeout = 6000): Promise<NetResult> {
+    if (!options.url.startsWith('/api')) {
+      options.url = '/api' + options.url
+    }
+    return this.fetch(options.url + '?' + (options.params ? Object.keys(options.params).map((obj: string) => `${obj}=${options.params[obj]}`).join('&') : ''), {
+      method: options.method,
+      headers: {
+        ...options.headers,
+        'Content-Type': 'application/json',
+        Authorization: this.tokenService.token
+      },
+      body: options.method == 'GET' ? undefined : JSON.stringify(options.params)
+    }, timeout)
+  }
+
+  /**
+   * fetch
+   * @param url 
+   * @param opt 
+   * @param timeout 0 默认不超时
+   * @returns 
+   */
+  private fetch(url: string, opt: RequestInit, timeout = 0): Promise<NetResult> {
     return new Promise((resolve) => {
     return new Promise((resolve) => {
       const controller = new AbortController()
       const controller = new AbortController()
       const { signal } = controller
       const { signal } = controller
-      setTimeout(() => {
-        controller.abort()
-      }, timeout)
-      fetch(urls + url, {
+      if (timeout) {
+        setTimeout(() => {
+          controller.abort()
+        }, timeout)
+      }
+      fetch(url, {
         signal,
         signal,
-        method: 'put',
-        headers: {
+        ...opt,
+        headers: opt.headers || {
           'Content-Type': 'application/json',
           'Content-Type': 'application/json',
-          Authorization: newToken
-        },
-        body: JSON.stringify(params)
-      }).then((res) => res.json()).then((res) => {
-        if (res.code !== 200) {
-          this.throw(res.msg, import.meta.url, 404)
+          Authorization: this.tokenService.token
+        }
+      }).then(res => {
+        if (res.status !== 200) {
+          throw res.status
+        }
+        return res.json()
+      }).then(res => {
+        if (res?.code !== 200) {
+          throw res?.msg || '接口调用失败'
         }
         }
         resolve({
         resolve({
-          success: res?.success,
+          success: res?.success || false,
           data: res?.data || null,
           data: res?.data || null,
           msg: res?.msg || null,
           msg: res?.msg || null,
-          code: res?.code || -1
+          code: res?.code || 200
         })
         })
-      }).catch((err: any) => {
+      }).catch((err: Any) => {
         resolve({
         resolve({
           success: false,
           success: false,
           data: null,
           data: null,
-          msg: `接口 [${url}] 错误: ${err?.message || err}`,
+          msg: `网络请求超时`,
           code: -1
           code: -1
         })
         })
-      })
-    })
-  }
-
-  /**
-   * upload上传文件接口
-   * @param url 接口地址
-   * @param params 接口参数
-   */
-  upload(url: string, params: any, timeout = 6000): Promise<NetResult> {
-    const newToken = `${storeService.tokenInfo.type} ${storeService.tokenInfo.access_token}`
-    return new Promise((resolve) => {
-      const controller = new AbortController()
-      const { signal } = controller
-      setTimeout(() => {
-        controller.abort()
-      }, timeout)
-
-      fetch(urls + url, {
-        signal,
-        method: 'POST',
-        headers: { Authorization: newToken },
-        body: params
-      }).then((res) => res.json()).then((res) => {
-        if (res.code !== 200) {
-          this.throw(res.msg, import.meta.url, 404)
+        if (err.code === 20) {
+          throw '网络请求超时'
+        }
+        let error = err?.message || err
+        if (typeof err === 'number') {
+          if (err === 401 || err === 404) {
+            if (window.electron) { window.electron.send('mainLoginOut') }
+            throw err
+          }
+          error = NET_ERRORS[err] || `系统错误 [${err}]`
         }
         }
-        resolve({
-          success: res?.success,
-          data: res?.data || null,
-          msg: res?.msg || null,
-          code: res?.code || -1
-        })
-      }).catch((err: any) => {
         resolve({
         resolve({
           success: false,
           success: false,
           data: null,
           data: null,
-          msg: `接口 [${url}] 错误: ${err?.message || err}`,
+          msg: `接口 [${url.split('?')[0]}] 错误: ${error}`,
           code: -1
           code: -1
         })
         })
+        throw error
       })
       })
     })
     })
   }
   }
-
-  /** token 续期 */
-  async refresh() {
-    await this.put('/upms/v3/auth/check_token')
-  }
 }
 }