Client: refactor

This commit is contained in:
Sam 2018-06-12 12:51:23 +02:00
parent b54f25357f
commit ca8a89915e
10 changed files with 69 additions and 163 deletions

View File

@ -287,10 +287,9 @@ def del_picture(user_id):
db.session.commit() db.session.commit()
response_object = { response_object = {
'status': 'success', 'status': 'no content'
'message': 'User picture delete.'
} }
return jsonify(response_object), 200 return jsonify(response_object), 204
except (exc.IntegrityError, ValueError) as e: except (exc.IntegrityError, ValueError) as e:
db.session.rollback() db.session.rollback()

View File

@ -1,7 +1,6 @@
import { parse } from 'date-fns' import { parse } from 'date-fns'
import FitTrackeeGenericApi from '../fitTrackeeApi' import FitTrackeeGenericApi from '../fitTrackeeApi'
import FitTrackeeApi from '../fitTrackeeApi/activities'
import { history } from '../index' import { history } from '../index'
import { formatChartData } from '../utils' import { formatChartData } from '../utils'
import { setError, setLoading } from './index' import { setError, setLoading } from './index'
@ -27,8 +26,8 @@ export const setChartData = chartData => ({
chartData, chartData,
}) })
export const addActivity = form => dispatch => FitTrackeeApi export const addActivity = form => dispatch => FitTrackeeGenericApi
.addActivity(form) .addDataWithFile('activities', form)
.then(ret => { .then(ret => {
if (ret.status === 'created') { if (ret.status === 'created') {
if (ret.data.activities.length === 0) { if (ret.data.activities.length === 0) {
@ -48,8 +47,8 @@ export const addActivity = form => dispatch => FitTrackeeApi
.catch(error => dispatch(setError(`activities: ${error}`))) .catch(error => dispatch(setError(`activities: ${error}`)))
export const addActivityWithoutGpx = form => dispatch => FitTrackeeApi export const addActivityWithoutGpx = form => dispatch => FitTrackeeGenericApi
.addActivityWithoutGpx(form) .addData('activities/no_gpx', form)
.then(ret => { .then(ret => {
if (ret.status === 'created') { if (ret.status === 'created') {
dispatch(loadProfile()) dispatch(loadProfile())
@ -63,8 +62,8 @@ export const addActivityWithoutGpx = form => dispatch => FitTrackeeApi
export const getActivityGpx = activityId => dispatch => { export const getActivityGpx = activityId => dispatch => {
if (activityId) { if (activityId) {
return FitTrackeeApi return FitTrackeeGenericApi
.getActivityGpx(activityId) .getData(`activities/${activityId}/gpx`)
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 'success') {
dispatch(setGpx(ret.data.gpx)) dispatch(setGpx(ret.data.gpx))
@ -80,8 +79,8 @@ export const getActivityGpx = activityId => dispatch => {
export const getActivityChartData = activityId => dispatch => { export const getActivityChartData = activityId => dispatch => {
if (activityId) { if (activityId) {
return FitTrackeeApi return FitTrackeeGenericApi
.getActivityChartData(activityId) .getData(`activities/${activityId}/chart_data`)
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 'success') {
dispatch(setChartData(formatChartData(ret.data.chart_data))) dispatch(setChartData(formatChartData(ret.data.chart_data)))

View File

@ -1,8 +1,8 @@
import FitTrackeeApi from '../fitTrackeeApi/stats' import FitTrackeeGenericApi from '../fitTrackeeApi'
import { setData, setError } from './index' import { setData, setError } from './index'
export const getStats = (userId, type, data) => dispatch => FitTrackeeApi export const getStats = (userId, type, data) => dispatch => FitTrackeeGenericApi
.getStats(userId, type, data) .getData(`stats/${userId}/${type}`, data)
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 'success') {
dispatch(setData('statistics', ret.data)) dispatch(setData('statistics', ret.data))

View File

@ -1,3 +1,4 @@
import FitTrackeeGenericApi from '../fitTrackeeApi'
import FitTrackeeApi from '../fitTrackeeApi/user' import FitTrackeeApi from '../fitTrackeeApi/user'
import { history } from '../index' import { history } from '../index'
import { generateIds } from '../utils' import { generateIds } from '../utils'
@ -18,8 +19,17 @@ const ProfileUpdateError = message => ({
type: 'PROFILE_UPDATE_ERROR', message type: 'PROFILE_UPDATE_ERROR', message
}) })
export const getProfile = () => dispatch => FitTrackeeApi export const logout = () => ({ type: 'LOGOUT' })
.getProfile()
export const loadProfile = () => dispatch => {
if (window.localStorage.getItem('authToken')) {
return dispatch(getProfile())
}
return { type: 'LOGOUT' }
}
export const getProfile = () => dispatch => FitTrackeeGenericApi
.getData('auth/profile')
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 'success') {
dispatch(getData('sports')) dispatch(getData('sports'))
@ -32,9 +42,8 @@ export const getProfile = () => dispatch => FitTrackeeApi
throw error throw error
}) })
export const loginOrRegister = (target, formData) => dispatch => FitTrackeeApi
export const register = formData => dispatch => FitTrackeeApi .loginOrRegister(target, formData)
.register(formData)
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 'success') {
window.localStorage.setItem('authToken', ret.auth_token) window.localStorage.setItem('authToken', ret.auth_token)
@ -46,29 +55,6 @@ export const register = formData => dispatch => FitTrackeeApi
throw error throw error
}) })
export const login = formData => dispatch => FitTrackeeApi
.login(formData)
.then(ret => {
if (ret.status === 'success') {
window.localStorage.setItem('authToken', ret.auth_token)
return dispatch(getProfile())
}
return dispatch(AuthError(ret.message))
})
.catch(error => {
throw error
})
export const loadProfile = () => dispatch => {
if (window.localStorage.getItem('authToken')) {
return dispatch(getProfile())
}
return { type: 'LOGOUT' }
}
export const logout = () => ({ type: 'LOGOUT' })
const RegisterFormControl = formData => { const RegisterFormControl = formData => {
const errMsg = [] const errMsg = []
if (formData.username.length < 3 || formData.username.length > 12) { if (formData.username.length < 3 || formData.username.length > 12) {
@ -84,16 +70,14 @@ const RegisterFormControl = formData => {
} }
export const handleUserFormSubmit = (formData, formType) => dispatch => { export const handleUserFormSubmit = (formData, formType) => dispatch => {
if (formType === 'Login') { if (formType === 'register') {
return dispatch(login(formData))
}
// formType === 'Register'
const ret = RegisterFormControl(formData) const ret = RegisterFormControl(formData)
if (ret.length === 0) { if (ret.length > 0) {
return dispatch(register(formData))
}
return dispatch(AuthErrors(generateIds(ret))) return dispatch(AuthErrors(generateIds(ret)))
} }
}
return dispatch(loginOrRegister(formType, formData))
}
export const handleProfileFormSubmit = formData => dispatch => { export const handleProfileFormSubmit = formData => dispatch => {
if (!formData.password === formData.password_conf) { if (!formData.password === formData.password_conf) {
@ -101,8 +85,8 @@ export const handleProfileFormSubmit = formData => dispatch => {
'Password and password confirmation don\'t match.' 'Password and password confirmation don\'t match.'
)) ))
} }
return FitTrackeeApi return FitTrackeeGenericApi
.updateProfile(formData) .postData('auth/profile/edit', formData)
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 'success') {
dispatch(getProfile()) dispatch(getProfile())
@ -120,8 +104,8 @@ export const uploadPicture = event => dispatch => {
const form = new FormData() const form = new FormData()
form.append('file', event.target.picture.files[0]) form.append('file', event.target.picture.files[0])
event.target.reset() event.target.reset()
return FitTrackeeApi return FitTrackeeGenericApi
.updatePicture(form) .addDataWithFile('auth/picture', form)
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 'success') {
return dispatch(getProfile()) return dispatch(getProfile())
@ -136,10 +120,10 @@ export const uploadPicture = event => dispatch => {
export const deletePicture = () => dispatch => FitTrackeeApi export const deletePicture = () => dispatch => FitTrackeeApi
.deletePicture() .deletePicture()
.then(ret => { .then(ret => {
if (ret.status === 'success') { if (ret.status === 204) {
return dispatch(getProfile()) return dispatch(getProfile())
} }
dispatch(PictureError(ret.message)) return dispatch(PictureError(ret.message))
}) })
.catch(error => { .catch(error => {
throw error throw error

View File

@ -43,7 +43,7 @@ export default class App extends React.Component {
<Redirect to="/" /> <Redirect to="/" />
) : ( ) : (
<UserForm <UserForm
formType={'Register'} formType={'register'}
/> />
) )
)} )}
@ -55,7 +55,7 @@ export default class App extends React.Component {
<Redirect to="/" /> <Redirect to="/" />
) : ( ) : (
<UserForm <UserForm
formType={'Login'} formType={'login'}
/> />
) )
)} )}
@ -68,7 +68,7 @@ export default class App extends React.Component {
<ProfileEdit /> <ProfileEdit />
) : ( ) : (
<UserForm <UserForm
formType={'Login'} formType={'login'}
/> />
) )
)} )}
@ -80,7 +80,7 @@ export default class App extends React.Component {
<Profile /> <Profile />
) : ( ) : (
<UserForm <UserForm
formType={'Login'} formType={'login'}
/> />
) )
)} )}

View File

@ -7,7 +7,9 @@ export default function Form (props) {
<Helmet> <Helmet>
<title>FitTrackee - {props.formType}</title> <title>FitTrackee - {props.formType}</title>
</Helmet> </Helmet>
<h1 className="page-title">{props.formType}</h1> <h1 className="page-title">
{`${props.formType.charAt(0).toUpperCase()}${props.formType.slice(1)}`}
</h1>
<div className="container"> <div className="container">
<div className="row"> <div className="row">
<div className="col-md-3" /> <div className="col-md-3" />
@ -16,7 +18,7 @@ export default function Form (props) {
<form onSubmit={event => <form onSubmit={event =>
props.handleUserFormSubmit(event, props.formType)} props.handleUserFormSubmit(event, props.formType)}
> >
{props.formType === 'Register' && {props.formType === 'register' &&
<div className="form-group"> <div className="form-group">
<input <input
className="form-control input-lg" className="form-control input-lg"
@ -51,7 +53,7 @@ export default function Form (props) {
onChange={props.onHandleFormChange} onChange={props.onHandleFormChange}
/> />
</div> </div>
{props.formType === 'Register' && {props.formType === 'register' &&
<div className="form-group"> <div className="form-group">
<input <input
className="form-control input-lg" className="form-control input-lg"

View File

@ -1,40 +0,0 @@
import { apiUrl, createRequest } from '../utils'
export default class FitTrackeeApi {
static addActivity(formData) {
const params = {
url: `${apiUrl}activities`,
method: 'POST',
body: formData,
}
return createRequest(params)
}
static addActivityWithoutGpx(data) {
const params = {
url: `${apiUrl}activities/no_gpx`,
method: 'POST',
body: data,
type: 'application/json',
}
return createRequest(params)
}
static getActivityGpx(activityId) {
const params = {
url: `${apiUrl}activities/${activityId}/gpx`,
method: 'GET',
}
return createRequest(params)
}
static getActivityChartData(activityId) {
const params = {
url: `${apiUrl}activities/${activityId}/chart_data`,
method: 'GET',
}
return createRequest(params)
}
}

View File

@ -29,6 +29,25 @@ export default class FitTrackeeApi {
return createRequest(params) return createRequest(params)
} }
static addDataWithFile(target, data) {
const params = {
url: `${apiUrl}${target}`,
method: 'POST',
body: data,
}
return createRequest(params)
}
static postData(target, data) {
const params = {
url: `${apiUrl}${target}/${data.id}`,
method: 'POST',
body: data,
type: 'application/json',
}
return createRequest(params)
}
static updateData(target, data) { static updateData(target, data) {
const params = { const params = {
url: `${apiUrl}${target}/${data.id}`, url: `${apiUrl}${target}/${data.id}`,

View File

@ -1,18 +0,0 @@
import { apiUrl, createRequest } from '../utils'
export default class FitTrackeeApi {
static getStats(userID, type, data = {}) {
let url = `${apiUrl}stats/${userID}/${type}`
if (Object.keys(data).length > 0) {
url += '?'
Object.keys(data).map(key => url += `&${key}=${data[key]}`)
}
const params = {
url: url,
method: 'GET',
}
return createRequest(params)
}
}

View File

@ -2,9 +2,9 @@ import { apiUrl, createRequest } from '../utils'
export default class FitTrackeeApi { export default class FitTrackeeApi {
static login(data) { static loginOrRegister(target, data) {
const params = { const params = {
url: `${apiUrl}auth/login`, url: `${apiUrl}auth/${target}`,
method: 'POST', method: 'POST',
noAuthorization: true, noAuthorization: true,
body: data, body: data,
@ -13,45 +13,6 @@ export default class FitTrackeeApi {
return createRequest(params) return createRequest(params)
} }
static register(data) {
const params = {
url: `${apiUrl}auth/register`,
method: 'POST',
noAuthorization: true,
body: data,
type: 'application/json',
}
return createRequest(params)
}
static getProfile() {
const params = {
url: `${apiUrl}auth/profile`,
method: 'GET',
type: 'application/json',
}
return createRequest(params)
}
static updateProfile(data) {
const params = {
url: `${apiUrl}auth/profile/edit`,
method: 'POST',
body: data,
type: 'application/json',
}
return createRequest(params)
}
static updatePicture(form) {
const params = {
url: `${apiUrl}auth/picture`,
method: 'POST',
body: form,
}
return createRequest(params)
}
static deletePicture() { static deletePicture() {
const params = { const params = {
url: `${apiUrl}auth/picture`, url: `${apiUrl}auth/picture`,