|
1 | 1 | import axios, { Method } from "axios"; |
2 | | -import { getAuthToken } from "./token"; |
3 | | -import { getTimeOut, isSandbox } from "./init"; |
| 2 | +import DanApi from "./constructor"; |
4 | 3 |
|
5 | 4 | const endpoints = { |
6 | 5 | sandbox: 'https://sandbox.dan.com/api/integrator/v1', |
7 | 6 | production: 'https://dan.com/api/integrator/v1' |
8 | 7 | }; |
9 | 8 |
|
10 | | -// Get the url of the endpoint |
11 | | -export function endpointUrl(path: string): string { |
12 | | - return `${endpoints[isSandbox() ? 'sandbox' : 'production']}${path}`; |
13 | | -} |
| 9 | +export function endpoint(api: DanApi) { |
| 10 | + // Get the url of the endpoint |
| 11 | + function url(path: string): string { |
| 12 | + return `${endpoints[api.isSandbox() ? 'sandbox' : 'production']}${path}`; |
| 13 | + } |
| 14 | + |
| 15 | + // Request the endpoint |
| 16 | + async function request(path: string, method: Method, data?: any) { |
| 17 | + const response = await axios({ |
| 18 | + method, |
| 19 | + url: url(path), |
| 20 | + data, |
| 21 | + timeout: api.getTimeOut(), |
| 22 | + headers: { |
| 23 | + Authorization: 'Bearer ' + (await api.auth.token()) |
| 24 | + } |
| 25 | + }); |
14 | 26 |
|
15 | | -// Request the endpoint |
16 | | -export async function request(path: string, method: Method, data?: any) { |
17 | | - const response = await axios({ |
18 | | - method, |
19 | | - url: endpointUrl(path), |
20 | | - data, |
21 | | - timeout: getTimeOut(), |
22 | | - headers: { |
23 | | - Authorization: 'Bearer ' + (await getAuthToken()) |
| 27 | + if (response.status !== 200) { |
| 28 | + throw new Error('Endpoint error'); |
24 | 29 | } |
25 | | - }); |
26 | 30 |
|
27 | | - if (response.status !== 200) { |
28 | | - throw new Error('Endpoint error'); |
| 31 | + return response.data; |
29 | 32 | } |
30 | 33 |
|
31 | | - return response.data; |
| 34 | + return { url, request }; |
32 | 35 | } |
0 commit comments