You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
2.2 KiB
78 lines
2.2 KiB
import { ExportTask } from '../panels/corpglory-dataexporter-panel/types'; |
|
|
|
import axios from 'axios'; |
|
import * as _ from 'lodash'; |
|
|
|
export const API_HOST = `${window.location.protocol}//${window.location.host}/`; |
|
export const API_PROXY_PREFIX = 'api/plugin-proxy/corpglory-dataexporter-app'; |
|
export const API_PATH_PREFIX = '/api'; |
|
|
|
const instance = axios.create(); |
|
|
|
instance.interceptors.request.use(function (config) { |
|
config.validateStatus = (status) => { |
|
return status >= 200 && status < 300; // default |
|
}; |
|
|
|
return { |
|
...config, |
|
}; |
|
}); |
|
|
|
interface RequestConfig { |
|
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS'; |
|
params?: any; |
|
data?: any; |
|
withCredentials?: boolean; |
|
validateStatus?: (status: number) => boolean; |
|
} |
|
|
|
export const queryApi = async <RT = any>(path: string, config: RequestConfig) => { |
|
const { method = 'GET', params, data, validateStatus } = config; |
|
|
|
const url = `${API_PROXY_PREFIX}${API_PATH_PREFIX}${path}`; |
|
|
|
const response = await instance({ |
|
method, |
|
url, |
|
params, |
|
data, |
|
validateStatus, |
|
}); |
|
|
|
return response.data as RT; |
|
}; |
|
|
|
export async function getTasks(dashboardUid: string): Promise<ExportTask[]> { |
|
return queryApi<ExportTask[]>('/task', { params: { dashboardUid } }); |
|
} |
|
|
|
export async function deleteTask(taskId?: string): Promise<void> { |
|
if (_.isEmpty(taskId)) { |
|
console.warn(`can't delete task without taskId`); |
|
return; |
|
} |
|
await queryApi<ExportTask[]>('/task', { method: 'DELETE', data: { taskId } }); |
|
} |
|
|
|
export async function getStaticFile(taskId?: string): Promise<void> { |
|
if (_.isEmpty(taskId)) { |
|
console.warn(`can't download file without taskId`); |
|
return; |
|
} |
|
const respData = await queryApi(`/static/${taskId}.csv`, {}); |
|
// TODO: check if resp exists |
|
// create file link in browser's memory |
|
const href = URL.createObjectURL(new Blob([respData], { type: 'text/csv' })); |
|
|
|
// create "a" HTML element with href to file & click |
|
const link = document.createElement('a'); |
|
link.href = href; |
|
link.setAttribute('download', `${taskId}.csv`); |
|
document.body.appendChild(link); |
|
link.click(); |
|
|
|
// clean up "a" element & remove ObjectURL |
|
document.body.removeChild(link); |
|
URL.revokeObjectURL(href); |
|
}
|
|
|