2023-11-08 14:52:14 +01:00

96 lines
2.7 KiB
JavaScript

class Network {
getEnvelope(envelopeKey) {
return fetch(`/api/envelope/${envelopeKey}`, this.withCSRFToken({ credentials: "include" }))
.then(res => res.json());
}
getDocument(envelopeKey, documentId) {
return fetch(`/api/document/${envelopeKey}?index=${documentId}`, this.withCSRFToken({ credentials: "include" }))
.then(res => res.arrayBuffer());
}
postDocument(envelopeKey, documentId, buffer) {
const url = `/api/document/${envelopeKey}?index=${documentId}`;
const options = {
credentials: "include",
method: "POST",
body: buffer
}
console.debug("PostDocument/Calling url: " + url)
return fetch(url, this.withCSRFToken(options))
.then(this.handleResponse)
.then((res) => {
if (!res.ok) {
return false;
};
return true;
});
}
postEnvelope(envelopeKey, documentId, jsonString) {
const url = `/api/envelope/${envelopeKey}?index=${documentId}`;
const options = {
credentials: "include",
method: "POST",
body: jsonString
}
console.debug("PostEnvelope/Calling url: " + url)
return fetch(url, this.withCSRFToken(options))
.then(this.handleResponse)
.then((res) => {
if (!res.ok) {
return false;
};
return true;
});
}
postHistory(envelopeKey, actionType, actionDescription) {
const url = `/api/history/${envelopeKey}`;
const data = {
actionDescription: actionDescription,
actionType: actionType.toString()
}
const options = {
credentials: "include",
method: "POST",
headers: {
'Content-Type': "application/json; charset=utf-8"
},
body: JSON.stringify(data)
}
console.debug("PostHistory/Calling url: " + url)
return fetch(url, this.withCSRFToken(options))
.then(this.handleResponse)
.then((res) => {
if (!res.ok) {
return false;
};
return true;
});
}
withCSRFToken(options) {
const token = (document.getElementsByName("__RequestVerificationToken")[0]).value;
let headers = options.headers;
options.headers = { ...headers, 'X-XSRF-TOKEN': token };
return options;
}
handleResponse(res) {
if (!res.ok) {
console.log(`Request failed with status ${res.status}`)
return res
} else {
return res
}
}
}