Jonathan Jenne c2de72be74 30-11-23
2023-11-30 14:00:30 +01:00

108 lines
2.5 KiB
JavaScript

class Network {
getEnvelope(envelopeKey) {
return fetch(
`/api/envelope/${envelopeKey}`,
this.withCSRFToken({ credentials: 'include' })
).then(this.wrapJsonResponse.bind(this))
}
getDocument(envelopeKey, documentId) {
return fetch(
`/api/document/${envelopeKey}?index=${documentId}`,
this.withCSRFToken({ credentials: 'include' })
).then(this.wrapBinaryResponse.bind(this))
}
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
})
}
openDocument(envelopeKey) {
const url = `/api/document/${envelopeKey}`
const options = {
credentials: 'include',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify({}),
}
console.debug('OpenDocument/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
}
async wrapJsonResponse(response) {
return await this.wrapResponse(response, async (res) => await res.json())
}
async wrapBinaryResponse(response) {
return await this.wrapResponse(
response,
async (res) => await res.arrayBuffer()
)
}
async wrapResponse(response, responseHandler) {
let wrappedResponse
if (response.ok) {
const data = await responseHandler(response)
wrappedResponse = new WrappedResponse(data, null)
} else {
const error = await response.json()
wrappedResponse = new WrappedResponse(null, error)
}
return wrappedResponse
}
handleResponse(res) {
if (!res.ok) {
console.log(`Request failed with status ${res.status}`)
return res
} else {
return res
}
}
}
class WrappedResponse {
constructor(data, error) {
this.data = data
this.error = error
}
}