You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bit4sat/web/src/api.js

136 lines
3.0 KiB
JavaScript

import 'babel-polyfill';
const endPoints = {
upload: '/api/v1/u',
session: '/api/v1/session',
pollstatus: '/api/v1/u/poll',
checkstatus: '/api/v1/u/check'
}
export async function lastSession(){
let req = new Request(endPoints.session, {
method: 'GET',
credentials: 'same-origin'
})
let res = await fetch(req)
.catch((e) => {console.error(e)})
return res.json()
}
export async function checkUploadStatus(uploadId){
let req = new Request(endPoints.checkstatus + '/' + uploadId,{
method: 'GET',
credentials: 'same-origin'
})
let res = await fetch(req)
if (!res.ok && res.status != 402){
let json = await res.json()
.catch((e)=>{
console.error(res.text())
})
console.error(`${res.status}: ` + json.error)
}
return res.json().catch((e)=>{console.error(e)})
}
export async function pollUploadStatus(uploadId){
//console.log('polling upload status')
let req = new Request(endPoints.pollstatus + '/' + uploadId,{
method: 'GET',
credentials: 'same-origin'
})
let res = await fetch(req)
.catch((e) => {console.error(e)})
return res.json().catch((e)=>{console.error(e)})
}
class Upload {
constructor(filesMetadata, fileObjects, options) {
this.filesMetadata = Array.from(filesMetadata)
this.fileObjects = fileObjects
this.timestamp = new Date()
this.options = options
}
get uploadMetadata() {
return {
files: this.filesMetadata,
timestamp: this.timestamp,
...this.options
}
}
async create() {
let req = new Request(endPoints.upload , {
method: 'POST',
credentials: 'same-origin',
body: JSON.stringify(this.uploadMetadata)
})
//let result = await fetch(req);
let res = await fetch(req)
.catch((e) => { console.error(e) })
return res.json().then(data => {
let { upload_id: id } = data
this.uploadId = id
return data
})
}
async checkstatus(){
return pollUploadStatus(this.uploadId)
}
async send(){
console.log(`Sending with id ${this.uploadId}`)
let formData = new FormData();
for (let file of this.fileObjects) {
formData.append('upload[]', file)
}
let req = new Request(endPoints.upload + '/' + this.uploadId, {
method: 'PUT',
credentials: 'same-origin',
body: formData
})
let res = await fetch(req)
.catch((e) => {console.error(e)})
return res.json()
}
}
export default {
endPoints: endPoints,
Upload: Upload,
pollUploadStatus: pollUploadStatus,
checkUploadStatus: checkUploadStatus
}