summaryrefslogtreecommitdiff
path: root/animism-align/frontend/api/crud.fetch.js
diff options
context:
space:
mode:
authorJules Laplace <julescarbon@gmail.com>2020-06-23 23:18:07 +0200
committerJules Laplace <julescarbon@gmail.com>2020-06-23 23:18:07 +0200
commit3cf70771cb45cc16ec33ffe44e7a1a4799d8f395 (patch)
tree55f0edb53141d5f043b486d722f507bfd94abdea /animism-align/frontend/api/crud.fetch.js
parent014816dc724c1be60b7dd28d4e608c89b4ed451c (diff)
adding web app base
Diffstat (limited to 'animism-align/frontend/api/crud.fetch.js')
-rw-r--r--animism-align/frontend/api/crud.fetch.js105
1 files changed, 105 insertions, 0 deletions
diff --git a/animism-align/frontend/api/crud.fetch.js b/animism-align/frontend/api/crud.fetch.js
new file mode 100644
index 0000000..c88225e
--- /dev/null
+++ b/animism-align/frontend/api/crud.fetch.js
@@ -0,0 +1,105 @@
+import fetch from 'node-fetch'
+
+export function crud_fetch(type, tag) {
+ const uri = '/api/v1/' + type + '/' + (tag || '')
+ return {
+ index: q => {
+ return fetch(_get_url(uri, q), _get_headers())
+ .then(req => req.json())
+ .catch(error)
+ },
+
+ show: id => {
+ let url;
+ if (typeof id === 'object') {
+ url = _get_url(uri + id[0] + '/', id[1])
+ } else {
+ url = _get_url(uri + id + '/')
+ }
+ return fetch(url, _get_headers())
+ .then(req => req.json())
+ .catch(error)
+ },
+
+ create: data => {
+ return fetch(uri, post(data))
+ .then(req => req.json())
+ .catch(error)
+ },
+
+ update: data => {
+ return fetch(uri + data.id + '/', put(data))
+ .then(req => req.json())
+ .catch(error)
+ },
+
+ destroy: data => {
+ return fetch(uri + data.id + '/', destroy(data))
+ .then(req => req.json())
+ .catch(error)
+ },
+ }
+}
+
+function _get_url(_url, data) {
+ const url = new URL(window.location.origin + _url)
+ if (data) {
+ Object.keys(data).forEach(key => url.searchParams.append(key, data[key]))
+ }
+ return url
+}
+export function _get_headers() {
+ return {
+ method: 'GET',
+ credentials: 'same-origin',
+ headers: {
+ 'Accept': 'application/json',
+ },
+ }
+}
+export function post(data) {
+ return {
+ method: 'POST',
+ body: JSON.stringify(data),
+ credentials: 'same-origin',
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json'
+ },
+ }
+}
+export function postBody(data) {
+ return {
+ method: 'POST',
+ body: data,
+ credentials: 'same-origin',
+ headers: {
+ 'Accept': 'application/json',
+ },
+ }
+}
+export function put(data) {
+ return {
+ method: 'PUT',
+ body: JSON.stringify(data),
+ credentials: 'same-origin',
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json'
+ },
+ }
+}
+export function destroy(data) {
+ return {
+ method: 'DELETE',
+ body: JSON.stringify(data),
+ credentials: 'same-origin',
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json'
+ },
+ }
+}
+function error(err) {
+ console.warn(err)
+}