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 // 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 // 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 = {}) { export default function makeService(endpoint, extensions = {}) {
const baseService = { const baseService = {
find(id, params) { find(id, params) {
console.log('api.js find'); console.log("api.js find")
const currentParams = new URLSearchParams(window.location.search); const currentParams = new URLSearchParams(window.location.search)
const combinedParams = { const combinedParams = {
...Object.fromEntries(currentParams), ...Object.fromEntries(currentParams),
...params, ...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) { findAll(params) {
console.log('api.js findAll'); console.log("api.js findAll")
console.log(params); console.log(params)
return fetch(endpoint, params); return fetch(endpoint, params)
}, },
async createWithFormData(payload) { async createWithFormData(payload) {
console.log('api.js createWithFormData'); console.log("api.js createWithFormData")
let formData = new FormData(); let formData = new FormData()
console.log('body'); console.log("body")
console.log(payload); console.log(payload)
if (payload) { if (payload) {
Object.keys(payload).forEach(function (key) { Object.keys(payload).forEach(function (key) {
// key: the name of the object key // key: the name of the object key
// index: the ordinal position of the key within the object // index: the ordinal position of the key within the object
formData.append(key, payload[key]); formData.append(key, payload[key])
console.log('options.key', key); console.log("options.key", key)
}); })
payload = formData; payload = formData
} }
return fetch(endpoint, { method: 'POST', body: payload}); return fetch(endpoint, { method: "POST", body: payload })
}, },
async create(payload) { async create(payload) {
console.log('api.js create'); console.log("api.js create")
console.log(payload); console.log(payload)
return fetch(endpoint, { method: 'POST', body: JSON.stringify(payload) }); return fetch(endpoint, { method: "POST", body: JSON.stringify(payload) })
}, },
del(item) { del(item) {
console.log('api.js del'); console.log("api.js del")
console.log(item['@id']); console.log(item["@id"])
return fetch(item['@id'], { method: 'DELETE' }); return fetch(item["@id"], { method: "DELETE" })
}, },
updateWithFormData(payload) { updateWithFormData(payload) {
console.log('api.js - update'); console.log("api.js - update")
return fetch(payload['@id'], { return fetch(payload["@id"], {
method: 'PUT', method: "PUT",
body: JSON.stringify(payload) body: JSON.stringify(payload),
}); })
}, },
update(payload) { update(payload) {
console.log('api.js - update'); console.log("api.js - update")
return fetch(payload['@id'], { return fetch(payload["@id"], {
method: 'PUT', method: "PUT",
body: JSON.stringify(payload) body: JSON.stringify(payload),
}); })
}, },
handleError(error, errorsRef, violationsRef) { handleError(error, errorsRef, violationsRef) {
if (error instanceof SubmissionError) { if (error instanceof SubmissionError) {
@ -74,8 +74,8 @@ export default function makeService(endpoint, extensions = {}) {
return return
} }
errorsRef.value = error.message errorsRef.value = error.message
} },
}; }
return { ...baseService, ...extensions }; return { ...baseService, ...extensions }
} }

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

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

Loading…
Cancel
Save