Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 797 | Rev 802 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
797 stevensc 1
import axios from 'axios'
2
 
3
export class Request {
4
  #client
5
  #abortController
6
 
7
  constructor(baseURL, timeout = 5000) {
8
    this.#client = axios.create({ baseURL, timeout })
801 stevensc 9
 
10
    this.#client.interceptors.request.use(
11
      async (request) => {
12
        const token = window.localStorage.getItem('jwt')
13
 
14
        if (token) {
15
          request.headers.Authorization = 'Bearer ' + token
16
        }
17
 
18
        if (['post', 'put', 'delete'].includes(request.method)) {
19
          try {
20
            const { data: responseData } = await this.MakeRequest.get('/csrf')
21
            const { data, success } = responseData
22
 
23
            if (success) {
24
              request.headers['X-CSRF-TOKEN'] = data
25
              return request
26
            }
27
          } catch (err) {
28
            throw new Error(
29
              `Axios problem with request during pre-flight phase: ${err}.`
30
            )
31
          }
32
        }
33
 
34
        if (['get'].includes(request.method)) {
35
          const headers = {
36
            Accept: 'application/json',
37
            Vary: 'Accept',
38
            'Cache-Control': 'no-cache, no-store',
39
            'Content-Type': 'application/json'
40
          }
41
          request.headers = { ...request.headers, ...headers }
42
          return request
43
        }
44
 
45
        return request
46
      },
47
      (error) => {
48
        return Promise.reject(error)
49
      }
50
    )
51
 
797 stevensc 52
    this.#abortController = new AbortController()
53
  }
54
 
55
  async MakeRequest(method = 'get', { endpoint, data, params }) {
56
    const config = { ...params }
57
    config.signal = this.#abortController.signal
58
 
59
    const response =
60
      method === 'get' || method === 'delete'
61
        ? await this.#client[method](endpoint, config)
62
        : await this.#client[method](endpoint, data, config)
63
 
64
    return response.data
65
  }
66
 
67
  async get(endpoint, params) {
68
    return await this.MakeRequest('get', { endpoint, params })
69
  }
70
 
71
  async delete(endpoint, params) {
72
    return await this.MakeRequest('delete', { endpoint, params })
73
  }
74
 
75
  async post(endpoint, data, params) {
76
    return await this.MakeRequest('post', { endpoint, data, params })
77
  }
78
 
79
  async put(endpoint, data, params) {
80
    return await this.MakeRequest('put', { endpoint, data, params })
81
  }
82
 
83
  cancelToken() {
84
    if (!this.#abortController.signal.aborted) {
85
      this.#abortController.abort()
86
    }
87
  }
88
}