FitTrackee/mpwo_client/src/actions/index.js

84 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-04-29 18:23:46 +02:00
import mpwoApi from '../mwpoApi/index'
2018-04-30 21:38:09 +02:00
import { history } from '../index'
2018-04-29 18:23:46 +02:00
export const setData = (target, data) => ({
type: 'SET_DATA',
data,
target,
})
2018-04-30 20:08:18 +02:00
export const setError = message => ({
2018-04-29 18:23:46 +02:00
type: 'SET_ERROR',
2018-04-30 20:08:18 +02:00
message,
2018-04-29 18:23:46 +02:00
})
2018-04-30 20:08:18 +02:00
export function getData(target, id = null) {
2018-04-29 18:23:46 +02:00
return function(dispatch) {
2018-04-30 20:08:18 +02:00
if (id !== null && isNaN(id)) {
return dispatch(setError(target, `${target}: Incorrect id`))
}
2018-04-29 18:23:46 +02:00
return mpwoApi
2018-04-30 20:08:18 +02:00
.getData(target, id)
2018-04-29 18:23:46 +02:00
.then(ret => {
if (ret.status === 'success') {
dispatch(setData(target, ret.data))
} else {
2018-04-30 20:08:18 +02:00
dispatch(setError(`${target}: ${ret.status}`))
2018-04-29 18:23:46 +02:00
}
})
2018-04-30 20:08:18 +02:00
.catch(error => dispatch(setError(`${target}: ${error}`)))
}
}
2018-04-30 21:38:09 +02:00
export function addData(target, data) {
return function(dispatch) {
return mpwoApi
.addData(target, data)
.then(ret => {
if (ret.status === 'created') {
2018-05-01 12:40:30 +02:00
history.push(`/admin/${target}`)
2018-04-30 21:38:09 +02:00
} else {
dispatch(setError(`${target}: ${ret.status}`))
}
})
.catch(error => dispatch(setError(`${target}: ${error}`)))
}
}
2018-04-30 20:08:18 +02:00
export function updateData(target, data) {
return function(dispatch) {
if (isNaN(data.id)) {
return dispatch(setError(target, `${target}: Incorrect id`))
}
return mpwoApi
.updateData(target, data)
.then(ret => {
if (ret.status === 'success') {
dispatch(setData(target, ret.data))
} else {
dispatch(setError(`${target}: ${ret.status}`))
}
2018-04-29 18:23:46 +02:00
})
2018-04-30 20:08:18 +02:00
.catch(error => dispatch(setError(`${target}: ${error}`)))
2018-04-29 18:23:46 +02:00
}
}
2018-04-30 21:38:09 +02:00
export function deleteData(target, id) {
return function(dispatch) {
if (isNaN(id)) {
return dispatch(setError(target, `${target}: Incorrect id`))
}
return mpwoApi
.deleteData(target, id)
.then(ret => {
if (ret.status === 204) {
history.push(`/admin/${target}`)
} else {
dispatch(setError(`${target}: ${ret.status}`))
}
})
.catch(error => dispatch(setError(`${target}: ${error}`)))
}
}