hrms-publish/src/api/document.ts
2023-12-22 13:58:19 +07:00

80 lines
1.7 KiB
TypeScript

import type { StorageFile } from '@/interface/response/storage'
const API_URI = import.meta.env.VITE_API_URI_CONFIG
export async function getDocumentList(volume: string, id: string) {
const res = await fetch(`${API_URI}/document/${volume}/${id}`, {
headers: {
Accept: 'application/json',
},
})
if (res && res.ok) {
return (await res.json()) as StorageFile
}
return false
}
export async function getDocumentInfo(
volume: string,
id: string,
file: string
) {
const res = await fetch(`${API_URI}/document/${volume}/${id}/${file}`, {
headers: {
Accept: 'application/json',
},
})
if (res && res.ok) {
return (await res.json()) as StorageFile & { downloadUrl: string }
}
return false
}
const util = {
formatBytes: (bytes: number, decimals = 2) => {
if (!+bytes) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = [
'Bytes',
'KiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB',
]
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
},
download: async (url: string, name?: string) => {
await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.blob())
.then((blob) => {
const a = document.createElement('a')
a.href = window.URL.createObjectURL(blob)
a.download = name ?? 'download'
a.click()
a.remove()
})
},
}
const doc = {
list: getDocumentList,
info: getDocumentInfo,
util,
}
export default doc