Files
django-cookAssistant/frontend/src/api.js
2019-04-20 22:15:25 +02:00

155 lines
3.2 KiB
JavaScript

/*
TODO:
Implement 'create'/'edit'/'read' modes with generic
configuration retrieved from OPTIONS request (using api.js)
'read' would use GET methods
'edit' would use PUT actions
'create' would use POST action
*/
const baseUrl = "http://localhost:8000/api"
/*
Check that the response status is what's expected.
Returns an object with :
* success: bool
* data: response data
*/
const processStatusCode = function(expected_code) {
return function(response) {
const status_code = response.status;
let data;
if (expected_code != 204) {
data = response.json();
} else {
data = null
}
return Promise.all([status_code, data])
.then(ret => ({
success: ret[0] == expected_code,
data: ret[1]
}))
}
}
/*
Returns data on success or throw an error with data.
*/
const processSuccess = function(result) {
if (!result.success) {
throw result.data;
}
return result.data;
}
const _headers = {
'Content-Type': 'application/json'
}
const _request = {
get (url) {
return fetch(
url,
{ method: 'GET',
})
.then(processStatusCode(200))
.then(processSuccess);
},
post (url, data) {
return fetch(
url,
{ method: 'POST',
body: JSON.stringify(data),
headers: _headers,
})
.then(processStatusCode(201))
.then(processSuccess)
},
put (url, data) {
return fetch(
url,
{ method: 'PUT',
body: JSON.stringify(data),
headers: _headers,
})
.then(processStatusCode(200))
.then(processSuccess)
},
delete(url) {
return fetch(
url,
{ method: 'DELETE',
headers: _headers, })
.then(processStatusCode(204))
.then(processSuccess)
},
options (url) {
return fetch(
url,
{ method: 'OPTIONS',
})
.then(processStatusCode(200))
.then(processSuccess)
}
}
const mountEndPoint = function(url) {
return {
read (id) {
return _request.get(url + id + '/')
},
create (data) {
return _request.post(url, data)
},
edit (id, data) {
return _request.put(url + id + '/', data)
},
delete (id) {
return _request.delete(url + id + '/')
},
options() { return _request.options(url) },
list () { return _request.get( url ) }
}
}
const mountNestedEndPoint = function(url) {
const getUrl = function(parent_id) {
// TODO: Make it safe against url injection !
return url.replace('*', parent_id)
}
return {
read (parent_id, id) {
return _request.get(getUrl(parent_id) + id + '/')
},
create (parent_id, data) {
return _request.post(
getUrl(parent_id),
data,
)
},
edit (parent_id, id, data) {
return _request.put(
getUrl(parent_id) + id + '/',
data,
)
},
delete (parent_id, id) {
return _request.delete( getUrl(parent_id) + id + '/' )
},
options () {
return _request.options( getUrl(1) )
},
list (parent_id) {
return _request.get( getUrl(parent_id) )
}
}
}
export default {
recipes: mountEndPoint(`${baseUrl}/recips/`),
ingredients: mountNestedEndPoint(
`${baseUrl}/recips/*/amounts/`
),
}