Minor: Format code

pull/5838/head
Angel Fernando Quiroz Campos 12 months ago
parent 30a60ebb28
commit 025ea4ff48
No known key found for this signature in database
GPG Key ID: B284841AE3E562CD
  1. 76
      assets/vue/services/api.js
  2. 352
      assets/vue/store/modules/crud.js
  3. 229
      assets/vue/utils/fetch.js

@ -1,4 +1,4 @@
import fetch from '../utils/fetch';
import fetch from "../utils/fetch"
// As stated here https://github.com/chamilo/chamilo-lms/pull/5386#discussion_r1578471409
// this service should not be used and instead the assets/bue/config/api.js should be used instead
@ -6,66 +6,66 @@ import fetch from '../utils/fetch';
export default function makeService(endpoint, extensions = {}) {
const baseService = {
find(id, params) {
console.log('api.js find');
const currentParams = new URLSearchParams(window.location.search);
console.log("api.js find")
const currentParams = new URLSearchParams(window.location.search)
const combinedParams = {
...Object.fromEntries(currentParams),
...params,
getFile: true
};
getFile: true,
}
const searchParams = new URLSearchParams(combinedParams);
const searchParams = new URLSearchParams(combinedParams)
return fetch(id, { params: Object.fromEntries(searchParams) });
return fetch(id, { params: Object.fromEntries(searchParams) })
},
findAll(params) {
console.log('api.js findAll');
console.log(params);
return fetch(endpoint, params);
console.log("api.js findAll")
console.log(params)
return fetch(endpoint, params)
},
async createWithFormData(payload) {
console.log('api.js createWithFormData');
console.log("api.js createWithFormData")
let formData = new FormData();
console.log('body');
console.log(payload);
let formData = new FormData()
console.log("body")
console.log(payload)
if (payload) {
Object.keys(payload).forEach(function (key) {
// key: the name of the object key
// index: the ordinal position of the key within the object
formData.append(key, payload[key]);
console.log('options.key', key);
});
payload = formData;
formData.append(key, payload[key])
console.log("options.key", key)
})
payload = formData
}
return fetch(endpoint, { method: 'POST', body: payload});
return fetch(endpoint, { method: "POST", body: payload })
},
async create(payload) {
console.log('api.js create');
console.log(payload);
return fetch(endpoint, { method: 'POST', body: JSON.stringify(payload) });
console.log("api.js create")
console.log(payload)
return fetch(endpoint, { method: "POST", body: JSON.stringify(payload) })
},
del(item) {
console.log('api.js del');
console.log(item['@id']);
return fetch(item['@id'], { method: 'DELETE' });
console.log("api.js del")
console.log(item["@id"])
return fetch(item["@id"], { method: "DELETE" })
},
updateWithFormData(payload) {
console.log('api.js - update');
console.log("api.js - update")
return fetch(payload['@id'], {
method: 'PUT',
body: JSON.stringify(payload)
});
return fetch(payload["@id"], {
method: "PUT",
body: JSON.stringify(payload),
})
},
update(payload) {
console.log('api.js - update');
console.log("api.js - update")
return fetch(payload['@id'], {
method: 'PUT',
body: JSON.stringify(payload)
});
return fetch(payload["@id"], {
method: "PUT",
body: JSON.stringify(payload),
})
},
handleError(error, errorsRef, violationsRef) {
if (error instanceof SubmissionError) {
@ -74,8 +74,8 @@ export default function makeService(endpoint, extensions = {}) {
return
}
errorsRef.value = error.message
}
};
},
}
return { ...baseService, ...extensions };
return { ...baseService, ...extensions }
}

@ -1,7 +1,7 @@
import { getField, updateField } from "vuex-map-fields";
import remove from "lodash/remove";
import SubmissionError from "../../error/SubmissionError";
import isEmpty from "lodash/isEmpty";
import { getField, updateField } from "vuex-map-fields"
import remove from "lodash/remove"
import SubmissionError from "../../error/SubmissionError"
import isEmpty from "lodash/isEmpty"
const initialState = () => ({
allIds: [],
@ -20,27 +20,27 @@ const initialState = () => ({
course: null,
session: null,
recents: [],
});
})
const handleError = (commit, e) => {
console.log("handleError");
commit(ACTIONS.TOGGLE_LOADING);
console.log(e);
console.log("handleError")
commit(ACTIONS.TOGGLE_LOADING)
console.log(e)
if (e instanceof SubmissionError) {
console.log("SubmissionError");
commit(ACTIONS.SET_VIOLATIONS, e.errors);
console.log("SubmissionError")
commit(ACTIONS.SET_VIOLATIONS, e.errors)
// eslint-disable-next-line
commit(ACTIONS.SET_ERROR, e.errors._error);
commit(ACTIONS.SET_ERROR, e.errors._error)
return Promise.reject(e);
return Promise.reject(e)
}
console.log("ACTIONS.SET_ERROR");
console.log("ACTIONS.SET_ERROR")
// eslint-disable-next-line
commit(ACTIONS.SET_ERROR, e.message);
commit(ACTIONS.SET_ERROR, e.message)
return Promise.reject(e);
};
return Promise.reject(e)
}
export const ACTIONS = {
ADD: "ADD",
@ -64,22 +64,22 @@ export const ACTIONS = {
ADD_COURSE: "ADD_COURSE",
ADD_SESSION: "ADD_SESSION",
REMOVE_SESSION: "REMOVE_SESSION",
};
}
export default function makeCrudModule({ normalizeRelations = (x) => x, resolveRelations = (x) => x, service } = {}) {
return {
actions: {
checkResponse(response) {
if (200 === response.status) {
return response.json();
return response.json()
}
return response;
return response
},
createWithFormData: ({ commit }, values) => {
console.log("createWithFormData");
commit(ACTIONS.SET_ERROR, "");
commit(ACTIONS.TOGGLE_LOADING);
console.log("createWithFormData")
commit(ACTIONS.SET_ERROR, "")
commit(ACTIONS.TOGGLE_LOADING)
return (
service
@ -91,58 +91,58 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
}
})*/
.then((data) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.ADD, data);
commit(ACTIONS.SET_CREATED, data);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.ADD, data)
commit(ACTIONS.SET_CREATED, data)
})
.catch((e) => handleError(commit, e))
);
)
},
create: ({ commit }, values) => {
console.log("crud.js create");
console.log(values);
commit(ACTIONS.SET_ERROR, "");
commit(ACTIONS.TOGGLE_LOADING);
console.log("crud.js create")
console.log(values)
commit(ACTIONS.SET_ERROR, "")
commit(ACTIONS.TOGGLE_LOADING)
return service
.create(values)
.then((response) => response.json())
.then((data) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.ADD, data);
commit(ACTIONS.SET_CREATED, data);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.ADD, data)
commit(ACTIONS.SET_CREATED, data)
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
del: ({ commit }, item) => {
console.log("del");
commit(ACTIONS.SET_ERROR, "");
commit(ACTIONS.TOGGLE_LOADING);
console.log("del")
commit(ACTIONS.SET_ERROR, "")
commit(ACTIONS.TOGGLE_LOADING)
return service
.del(item)
.then(() => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.SET_DELETED, item);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.SET_DELETED, item)
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
delMultiple: ({ commit }, items) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.TOGGLE_LOADING)
const promises = items.map(async (item) => {
const result = await service.del(item);
const result = await service.del(item)
commit(ACTIONS.SET_DELETED_MULTIPLE, item);
commit(ACTIONS.SET_DELETED_MULTIPLE, item)
return result;
});
return result
})
return Promise.all(promises).then(() => {
commit(ACTIONS.TOGGLE_LOADING);
});
commit(ACTIONS.TOGGLE_LOADING)
})
},
findAll: ({ commit, state }, params) => {
if (!service) throw new Error("No service specified!");
if (!service) throw new Error("No service specified!")
//commit(ACTIONS.TOGGLE_LOADING);
@ -150,281 +150,281 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
.findAll({ params })
.then((response) => response.json())
.then((retrieved) => {
console.log("result of retrieved");
console.log("result of retrieved")
//commit(ACTIONS.TOGGLE_LOADING);
return retrieved["hydra:member"];
return retrieved["hydra:member"]
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
fetchAll: ({ commit, state }, params) => {
if (!service) throw new Error("No service specified!");
if (!service) throw new Error("No service specified!")
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.TOGGLE_LOADING)
return service
.findAll({ params })
.then((response) => response.json())
.then((retrieved) => {
console.log("result of retrieved");
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.SET_TOTAL_ITEMS, retrieved["hydra:totalItems"]);
commit(ACTIONS.SET_VIEW, retrieved["hydra:view"]);
commit(ACTIONS.SET_RECENTS, retrieved["hydra:member"]);
console.log("result of retrieved")
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.SET_TOTAL_ITEMS, retrieved["hydra:totalItems"])
commit(ACTIONS.SET_VIEW, retrieved["hydra:view"])
commit(ACTIONS.SET_RECENTS, retrieved["hydra:member"])
if (true === state.resetList) {
commit(ACTIONS.RESET_LIST);
commit(ACTIONS.RESET_LIST)
}
retrieved["hydra:member"].forEach((item) => {
commit(ACTIONS.ADD, normalizeRelations(item));
});
commit(ACTIONS.ADD, normalizeRelations(item))
})
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
fetchSelectItems: ({ commit }, { params = { properties: ["@id", "name"] } } = {}) => {
console.log("fetchSelectItems");
commit(ACTIONS.TOGGLE_LOADING);
if (!service) throw new Error("No service specified!");
console.log("fetchSelectItems")
commit(ACTIONS.TOGGLE_LOADING)
if (!service) throw new Error("No service specified!")
return service
.findAll({ params })
.then((response) => response.json())
.then((retrieved) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.SET_SELECT_ITEMS, retrieved["hydra:member"]);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.SET_SELECT_ITEMS, retrieved["hydra:member"])
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
loadWithQuery: ({ commit }, params = {}) => {
if (!service) throw new Error("No service specified!");
if (!service) throw new Error("No service specified!")
const id = params["id"];
delete params["id"];
const id = params["id"]
delete params["id"]
if (isEmpty(id)) {
throw new Error("Incorrect id");
throw new Error("Incorrect id")
}
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.TOGGLE_LOADING)
service
.find(id, params)
//.then(response => service.checkResponse(response))
.then((response) => {
if (200 === response.status) {
return response.json();
return response.json()
}
})
.then((item) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.ADD, normalizeRelations(item));
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.ADD, normalizeRelations(item))
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
load: ({ commit }, id) => {
if (!service) throw new Error("No service specified!");
console.log("crud load");
if (!service) throw new Error("No service specified!")
console.log("crud load")
if (isEmpty(id)) {
throw new Error("Incorrect id");
throw new Error("Incorrect id")
}
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.TOGGLE_LOADING)
return (
service
.find(id)
//.then(response => service.checkResponse(response))
.then((response) => {
if (200 === response.status) {
return response.json();
return response.json()
}
})
.then((item) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.ADD, normalizeRelations(item));
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.ADD, normalizeRelations(item))
return item;
return item
})
.catch((e) => handleError(commit, e))
);
)
},
findCourse: ({ commit }, params) => {
const id = params["id"];
delete params["id"];
if (!service) throw new Error("No service specified!");
console.log("findCourse");
commit(ACTIONS.TOGGLE_LOADING);
const id = params["id"]
delete params["id"]
if (!service) throw new Error("No service specified!")
console.log("findCourse")
commit(ACTIONS.TOGGLE_LOADING)
return service
.find(id, params)
.then((response) => {
if (200 === response.status) {
return response.json();
return response.json()
}
})
.then((item) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.ADD_COURSE, item);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.ADD_COURSE, item)
return item;
return item
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
cleanSession: ({ commit }) => {
commit(ACTIONS.REMOVE_SESSION);
commit(ACTIONS.REMOVE_SESSION)
},
findSession: ({ commit }, params) => {
const id = params["id"];
delete params["id"];
if (!service) throw new Error("No service specified!");
commit(ACTIONS.TOGGLE_LOADING);
const id = params["id"]
delete params["id"]
if (!service) throw new Error("No service specified!")
commit(ACTIONS.TOGGLE_LOADING)
return service
.find(id, params)
.then((response) => {
if (200 === response.status) {
return response.json();
return response.json()
}
})
.then((item) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.ADD_SESSION, item);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.ADD_SESSION, item)
return item;
return item
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
findResourceNode: ({ commit }, params) => {
const id = params["id"];
delete params["id"];
console.log("findResourceNode", id);
if (!service) throw new Error("No service specified!");
const id = params["id"]
delete params["id"]
console.log("findResourceNode", id)
if (!service) throw new Error("No service specified!")
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.TOGGLE_LOADING)
return service
.find(id, params)
.then((response) => {
if (200 === response.status) {
return response.json();
return response.json()
}
})
.then((item) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.ADD_RESOURCE_NODE, item);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.ADD_RESOURCE_NODE, item)
return item;
return item
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
resetCreate: ({ commit }) => {
commit(ACTIONS.RESET_CREATE);
commit(ACTIONS.RESET_CREATE)
},
resetDelete: ({ commit }) => {
commit(ACTIONS.RESET_DELETE);
commit(ACTIONS.RESET_DELETE)
},
resetShow: ({ commit }) => {
commit(ACTIONS.RESET_SHOW);
commit(ACTIONS.RESET_SHOW)
},
resetList: ({ commit }) => {
commit(ACTIONS.RESET_LIST);
commit(ACTIONS.RESET_LIST)
},
resetUpdate: ({ commit }) => {
commit(ACTIONS.RESET_UPDATE);
commit(ACTIONS.RESET_UPDATE)
},
update: ({ commit }, item) => {
console.log("crud update");
commit(ACTIONS.TOGGLE_LOADING);
console.log("crud update")
commit(ACTIONS.TOGGLE_LOADING)
return service
.update(item)
.then((response) => response.json())
.then((data) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.SET_UPDATED, data);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.SET_UPDATED, data)
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
updateWithFormData: ({ commit }, item) => {
console.log("crud updateWithFormData");
commit(ACTIONS.TOGGLE_LOADING);
console.log("crud updateWithFormData")
commit(ACTIONS.TOGGLE_LOADING)
return service
.updateWithFormData(item)
.then((response) => response.json())
.then((data) => {
commit(ACTIONS.TOGGLE_LOADING);
commit(ACTIONS.SET_UPDATED, data);
commit(ACTIONS.TOGGLE_LOADING)
commit(ACTIONS.SET_UPDATED, data)
})
.catch((e) => handleError(commit, e));
.catch((e) => handleError(commit, e))
},
},
getters: {
find: (state) => (id) => {
return resolveRelations(state.byId[id]);
return resolveRelations(state.byId[id])
},
getField,
list: (state, getters) => {
return state.allIds.map((id) => getters.find(id));
return state.allIds.map((id) => getters.find(id))
},
getResourceNode: (state) => {
return state.resourceNode;
return state.resourceNode
},
getCourse: (state) => {
return state.course;
return state.course
},
getSession: (state) => {
return state.session;
return state.session
},
getDeleted(state) {
return state.deleted;
return state.deleted
},
getTotalItems: (state) => {
return state.totalItems;
return state.totalItems
},
getRecents: (state) => {
return state.recents;
return state.recents
},
isLoading(state) {
return state.isLoading;
return state.isLoading
},
},
mutations: {
updateField,
[ACTIONS.ADD_COURSE]: (state, item) => {
state.course = item;
state.isLoading = false;
state.course = item
state.isLoading = false
//this.$set(state, 'resourceNode', item);
//this.$set(state, 'isLoading', false);
},
[ACTIONS.ADD_SESSION]: (state, item) => {
state.session = item;
state.isLoading = false;
state.session = item
state.isLoading = false
//this.$set(state, 'resourceNode', item);
//this.$set(state, 'isLoading', false);
},
[ACTIONS.REMOVE_SESSION]: (state) => {
state.session = null;
state.isLoading = false;
state.session = null
state.isLoading = false
//this.$set(state, 'resourceNode', item);
//this.$set(state, 'isLoading', false);
},
[ACTIONS.ADD_RESOURCE_NODE]: (state, item) => {
state.resourceNode = item;
state.isLoading = false;
state.resourceNode = item
state.isLoading = false
//this.$set(state, 'resourceNode', item);
//this.$set(state, 'isLoading', false);
},
[ACTIONS.ADD]: (state, item) => {
//this.$set(state.byId, item['@id'], item);
state.byId[item["@id"]] = item;
state.isLoading = false;
state.byId[item["@id"]] = item
state.isLoading = false
//this.$set(state, 'isLoading', false);
if (state.allIds.includes(item["@id"])) {
return;
return
}
state.allIds.push(item["@id"]);
state.allIds.push(item["@id"])
},
[ACTIONS.SET_RECENTS]: (state, items) => (state.recents = items),
[ACTIONS.RESET_CREATE]: (state) => {
@ -433,14 +433,14 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
error: "",
created: null,
violations: null,
});
})
},
[ACTIONS.RESET_DELETE]: (state) => {
Object.assign(state, {
isLoading: false,
error: "",
deleted: null,
});
})
},
[ACTIONS.RESET_LIST]: (state) => {
Object.assign(state, {
@ -449,13 +449,13 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
error: "",
isLoading: false,
resetList: false,
});
})
},
[ACTIONS.RESET_SHOW]: (state) => {
Object.assign(state, {
error: "",
isLoading: false,
});
})
},
[ACTIONS.RESET_UPDATE]: (state) => {
Object.assign(state, {
@ -463,27 +463,27 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
isLoading: false,
updated: null,
violations: null,
});
})
},
[ACTIONS.SET_CREATED]: (state, created) => {
//console.log('set _created');
//console.log(created);
Object.assign(state, { created });
state.created = created;
Object.assign(state, { created })
state.created = created
},
[ACTIONS.SET_DELETED]: (state, deleted) => {
//console.log('SET_DELETED');
if (!state.allIds.includes(deleted["@id"])) {
return;
return
}
Object.assign(state, {
allIds: remove(state.allIds, (item) => item["@id"] === deleted["@id"]),
byId: remove(state.byId, (id) => id === deleted["@id"]),
deleted,
});
})
},
[ACTIONS.SET_DELETED_MULTIPLE]: (state, deleted) => {
console.log("SET_DELETED_MULTIPLE");
console.log("SET_DELETED_MULTIPLE")
//console.log(deleted['@id']);
/*if (!state.allIds.includes(deleted['@id'])) {
return;
@ -492,11 +492,11 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
allIds: remove(state.allIds, (item) => item["@id"] === deleted["@id"]),
byId: remove(state.byId, (id) => id === deleted["@id"]),
deleted,
});
})
},
[ACTIONS.SET_ERROR]: (state, error) => {
state.error = error;
state.isLoading = false;
state.error = error
state.isLoading = false
//Object.assign(state, { error, isLoading: false });
},
[ACTIONS.SET_SELECT_ITEMS]: (state, selectItems) => {
@ -504,17 +504,17 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
error: "",
isLoading: false,
selectItems,
});
})
},
[ACTIONS.SET_TOTAL_ITEMS]: (state, totalItems) => {
Object.assign(state, { totalItems });
Object.assign(state, { totalItems })
},
[ACTIONS.SET_UPDATED]: (state, updated) => {
console.log("SET_UPDATED");
console.log(updated);
state.byId[updated["@id"]] = updated;
state.isLoading = false;
state.updated = updated;
console.log("SET_UPDATED")
console.log(updated)
state.byId[updated["@id"]] = updated
state.isLoading = false
state.updated = updated
/*Object.assign(state, {
byId: {
[updated['@id']]: updated
@ -523,16 +523,16 @@ export default function makeCrudModule({ normalizeRelations = (x) => x, resolveR
});*/
},
[ACTIONS.SET_VIEW]: (state, view) => {
Object.assign(state, { view });
Object.assign(state, { view })
},
[ACTIONS.SET_VIOLATIONS]: (state, violations) => {
Object.assign(state, { violations });
Object.assign(state, { violations })
},
[ACTIONS.TOGGLE_LOADING]: (state) => {
Object.assign(state, { error: "", isLoading: !state.isLoading });
Object.assign(state, { error: "", isLoading: !state.isLoading })
},
},
namespaced: true,
state: initialState,
};
}
}

@ -1,141 +1,132 @@
import { isArray, isObject, isUndefined, forEach } from 'lodash';
import { ENTRYPOINT } from '../config/entrypoint';
import SubmissionError from '../error/SubmissionError';
import { normalize } from './hydra';
const MIME_TYPE = 'application/ld+json';
const makeParamArray = (key, arr) =>
arr.map(val => `${key}[]=${val}`).join('&');
export default function(id, options = {}) {
console.log('fetch');
console.log(options);
if ("undefined" === typeof options.headers) {
options.headers = {};
}
if (!options.headers.hasOwnProperty("Accept")) {
options.headers = { ...options.headers, Accept: MIME_TYPE };
}
if (
undefined !== options.body &&
!(options.body instanceof FormData) &&
!options.headers.hasOwnProperty("Content-Type")
) {
options.headers = { ...options.headers, "Content-Type": MIME_TYPE };
}
if (options.params) {
const params = normalize(options.params);
let queryString = Object.keys(params)
.map(key =>
Array.isArray(params[key])
? makeParamArray(key, params[key])
: `${key}=${params[key]}`
)
.join('&');
id = `${id}?${queryString}`;
console.log('URL', id);
}
const entryPoint = ENTRYPOINT + (ENTRYPOINT.endsWith('/') ? '' : '/');
if ('PUT' === options.method) {
const payload = options.body && JSON.parse(options.body);
if (isObject(payload) && payload['@id']) {
options.body = JSON.stringify(normalize(payload));
}
}
/*const payload = options.body && JSON.parse(options.body);
import { isObject } from "lodash"
import { ENTRYPOINT } from "../config/entrypoint"
import SubmissionError from "../error/SubmissionError"
import { normalize } from "./hydra"
const MIME_TYPE = "application/ld+json"
const makeParamArray = (key, arr) => arr.map((val) => `${key}[]=${val}`).join("&")
export default function (id, options = {}) {
console.log("fetch")
console.log(options)
if ("undefined" === typeof options.headers) {
options.headers = {}
}
if (!options.headers.hasOwnProperty("Accept")) {
options.headers = { ...options.headers, Accept: MIME_TYPE }
}
if (
undefined !== options.body &&
!(options.body instanceof FormData) &&
!options.headers.hasOwnProperty("Content-Type")
) {
options.headers = { ...options.headers, "Content-Type": MIME_TYPE }
}
if (options.params) {
const params = normalize(options.params)
let queryString = Object.keys(params)
.map((key) => (Array.isArray(params[key]) ? makeParamArray(key, params[key]) : `${key}=${params[key]}`))
.join("&")
id = `${id}?${queryString}`
console.log("URL", id)
}
const entryPoint = ENTRYPOINT + (ENTRYPOINT.endsWith("/") ? "" : "/")
if ("PUT" === options.method) {
const payload = options.body && JSON.parse(options.body)
if (isObject(payload) && payload["@id"]) {
options.body = JSON.stringify(normalize(payload));
}*/
/*if (useAxios) {
console.log('axios');
let url = new URL(id, entryPoint);
console.log(formData);
return axios({
url: url.toString(),
method: 'POST',
//headers: options.headers,
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: function (progressEvent) {
console.log('progress');
//console.log(progressEvent);
console.log(options.body);
let uploadPercentage = parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100));
options.body['__progress'] = uploadPercentage;
options.body['__progressLabel'] = uploadPercentage;
this.uploadPercentage = uploadPercentage;
console.log(options.body);
//options.body.set('__progressLabel', uploadPercentage);
}.bind(this)
}
).then(response => {
options.body['__uploaded'] = 1;
options.body['uploadFile']['__uploaded'] = 1
options.body = JSON.stringify(normalize(payload))
}
}
/*const payload = options.body && JSON.parse(options.body);
if (isObject(payload) && payload["@id"]) {
options.body = JSON.stringify(normalize(payload));
}*/
/*if (useAxios) {
console.log('axios');
let url = new URL(id, entryPoint);
console.log(formData);
return axios({
url: url.toString(),
method: 'POST',
//headers: options.headers,
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: function (progressEvent) {
console.log('progress');
//console.log(progressEvent);
console.log(options.body);
let uploadPercentage = parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100));
options.body['__progress'] = uploadPercentage;
options.body['__progressLabel'] = uploadPercentage;
this.uploadPercentage = uploadPercentage;
console.log(options.body);
//options.body.set('__progressLabel', uploadPercentage);
}.bind(this)
}
).then(response => {
options.body['__uploaded'] = 1;
options.body['uploadFile']['__uploaded'] = 1
console.log(response);
console.log('SUCCESS!!');
console.log(response);
console.log('SUCCESS!!');
return response.data;
})
.catch(function (response) {
console.log(response);
console.log('FAILURE!!');
});
}*/
return response.data;
})
.catch(function (response) {
console.log(response);
console.log('FAILURE!!');
});
}*/
console.log('ready to fetch');
console.log("ready to fetch")
return global.fetch(new URL(id, entryPoint), options).then(response => {
console.log(response, 'global.fetch');
return global.fetch(new URL(id, entryPoint), options).then((response) => {
console.log(response, "global.fetch")
if (response.ok) {
return response;
return response
}
return response.json().then(json => {
let error =
json['hydra:description'] ||
json['hydra:title'] ||
'An error occurred.';
return response.json().then(
(json) => {
let error = json["hydra:description"] || json["hydra:title"] || "An error occurred."
if (json['code'] && 401 === json['code']) {
error = 'Not allowed';
if (json["code"] && 401 === json["code"]) {
error = "Not allowed"
}
if (json['error']) {
error = json['error'];
if (json["error"]) {
error = json["error"]
}
console.log(error, 'fetch error');
console.log(error, "fetch error")
if (!json.violations) {
console.log('violations');
throw Error(error);
console.log("violations")
throw Error(error)
}
let errors = { _error: error };
json.violations.map(
violation => (errors[violation.propertyPath] = violation.message)
);
let errors = { _error: error }
json.violations.map((violation) => (errors[violation.propertyPath] = violation.message))
throw new SubmissionError(errors);
throw new SubmissionError(errors)
},
() => {
console.log('error3');
throw new Error(response.statusText || 'An error occurred.');
}
);
});
console.log("error3")
throw new Error(response.statusText || "An error occurred.")
},
)
})
}

Loading…
Cancel
Save