refactor AppService exceptions && add JSDoc

develop
TBS093A 2020-08-11 20:36:33 +02:00
parent c44da28f4f
commit 13914f4283
7 changed files with 148 additions and 85 deletions

View File

@ -42,7 +42,7 @@ const AlbumCreate = ({
album, album,
user.token user.token
).then( response => { ).then( response => {
setMessage( response['info'] ) setMessage( response['info'] + '\n' )
}) })
} }
@ -81,7 +81,7 @@ const AlbumCreate = ({
titleInput.current.value = '' titleInput.current.value = ''
descriptionInput.current.value = '' descriptionInput.current.value = ''
setConsoleHistory( consoleHistory + message + '\n' ) setConsoleHistory( consoleHistory + message )
setComponentVisible( false ) setComponentVisible( false )
setImage('') setImage('')
setImageInfo('Drop/Click\nfor upload album image...') setImageInfo('Drop/Click\nfor upload album image...')

View File

@ -25,11 +25,7 @@ const AlbumDelete = ({
id, id,
user.token user.token
).then( response => { ).then( response => {
if ( response.detail !== 'Not found.' ){ setMessage( response['info'] + '\n' )
setMessage('album delete success')
} else{
setMessage('album delete failed')
}
}) })
} }
} }
@ -45,7 +41,7 @@ const AlbumDelete = ({
idInput.current.value = '' idInput.current.value = ''
setConsoleHistory( consoleHistory + message + '\n' ) setConsoleHistory( consoleHistory + message )
setComponentVisible( false ) setComponentVisible( false )
setMessage('') setMessage('')
} }

View File

@ -13,27 +13,26 @@ const AlbumGetAll = ({
}) => { }) => {
const [message, setMessage] = useState('') const [message, setMessage] = useState('')
const [oneRequest, setOne ] = useState(false) const [oneRequest, setOne] = useState(false)
useEffect( useEffect(
() => { () => {
if (componentVisible && oneRequest === false) { if (componentVisible && oneRequest === false) {
getAllAlbum() getAllAlbum().then(response => {
.then( response => { setMessage(
setMessage( mapAlbumsToString(
mapAlbumsToString( response['response'] ) response['response']
+ response['info'] ) + response['info'] + '\n'
) )
console.log( response ) })
}) setOne(!oneRequest)
setOne( !oneRequest )
} else { } else {
activateConsoleInput() activateConsoleInput()
} }
if ( message !== '' ) { if (message !== '') {
setConsoleHistory(consoleHistory + message) setConsoleHistory(consoleHistory + message)
setComponentVisible(false) setComponentVisible(false)
setOne( !oneRequest ) setOne(!oneRequest)
setMessage('') setMessage('')
} }
} }
@ -42,16 +41,16 @@ const AlbumGetAll = ({
const mapAlbumsToString = (albums) => { const mapAlbumsToString = (albums) => {
let list = '.albums\n' let list = '.albums\n'
for (let i = 0; i < albums.length; i++) { for (let i = 0; i < albums.length; i++) {
if ( i !== albums.length - 1 ) if (i !== albums.length - 1)
list += '├── ' + albums[i].title + '\n' list += '├── ' + albums[i].title + '\n'
+ '│ ├── id: ' + albums[i].id + '\n' + '│ ├── id: ' + albums[i].id + '\n'
+ '│ ├── user id: ' + albums[i].user_id + '\n' + '│ ├── user id: ' + albums[i].user_id + '\n'
+ '│ └── url: ' + albums[i].url_code + '\n' + '│ └── url: ' + albums[i].url_code + '\n'
else else
list += '└── ' + albums[i].title + '\n' list += '└── ' + albums[i].title + '\n'
+ ' ├── id: ' + albums[i].id + '\n' + ' ├── id: ' + albums[i].id + '\n'
+ ' ├── user id: ' + albums[i].user_id + '\n' + ' ├── user id: ' + albums[i].user_id + '\n'
+ ' └── url: ' + albums[i].url_code + '\n' + ' └── url: ' + albums[i].url_code + '\n'
} }
return list return list
} }

View File

@ -22,15 +22,18 @@ const AlbumGetOne = ({
setConsoleHistory( consoleHistory + 'album id: ' + inputValue + '\n') setConsoleHistory( consoleHistory + 'album id: ' + inputValue + '\n')
if ( inputValue >= 0 ) { if ( inputValue >= 0 ) {
getOneAlbum( inputValue ).then( response => { getOneAlbum( inputValue ).then( response => {
if ( response.detail !== 'Not found.' ){ if ( response['info'] !== 'Not found.' ){
setMessage( setMessage(
response.title + '\n' response['response'].title + '\n'
+ '├── id: ' + response.id + '\n' + '├── id: ' + response['response'].id + '\n'
+ '├── user id: ' + response.user_id + '\n' + '├── user id: ' + response['response'].user_id + '\n'
+ '└── url: ' + response.url_code + '\n' + '└── url: ' + response['response'].url_code + '\n'
+ response['info'] + '\n'
) )
} else{ } else{
setMessage('album not found') setMessage(
response['info'] + '\n'
)
} }
}) })
} }

View File

@ -50,10 +50,8 @@ const AlbumUpdate = ({
id, id,
album, album,
user.token user.token
).then( () => { ).then( response => {
setMessage('album update success') setMessage( response['info'] + '\n' )
}).catch( () => {
setMessage('album update failed')
}) })
} }
@ -71,7 +69,7 @@ const AlbumUpdate = ({
descriptionInput.current.value = '' descriptionInput.current.value = ''
imageInput.current.value = '' imageInput.current.value = ''
setConsoleHistory( consoleHistory + message + '\n' ) setConsoleHistory( consoleHistory + message )
setComponentVisible( false ) setComponentVisible( false )
setMessage('') setMessage('')
} }

View File

@ -1,38 +1,77 @@
import { address } from './APIAddress' import { address } from './APIAddress'
// session Token // User Session Token
let defaultToken = 'empty token' let defaultToken = 'empty token'
// CRUD methods // CRUD methods
/**
* get list method
* @param {string} endpoint - for example `user/`
*/
const _getList = async (endpoint) => { const _getList = async (endpoint) => {
return await responseGD(address + endpoint, 'GET', defaultToken) return await responseGD(address + endpoint, 'GET', defaultToken)
} }
/**
* get one row / record
* @param {string} endpoint - for example `user/`
*/
const _getOne = async (endpoint) => { const _getOne = async (endpoint) => {
return await responseGD(address + endpoint, 'GET', defaultToken) return await responseGD(address + endpoint, 'GET', defaultToken)
} }
/**
* universal post method
* @param {string} endpoint - for example `user/`
* @param {{}} body - body request
* @param {string} token - token for verify user in API
*/
const _post = async (endpoint, body, token) => { const _post = async (endpoint, body, token) => {
return await responseCRU(address + endpoint, 'POST', body, token) return await responseCRU(address + endpoint, 'POST', body, token)
} }
/**
* universal put method
* @param {string} endpoint - for example `user/{id}/` where {id} is object id
* @param {{}} body - body request
* @param {string} token - token for verify user in API
*/
const _put = async (endpoint, body, token) => { const _put = async (endpoint, body, token) => {
return await responseCRU(address + endpoint, 'PUT', body, token) return await responseCRU(address + endpoint, 'PUT', body, token)
} }
/**
* universal patch method
* @param {string} endpoint - for example `user/{id}/` where {id} is object id
* @param {{}} body - body request
* @param {string} token - token for verify user in API
*/
const _patch = async (endpoint, body, token) => { const _patch = async (endpoint, body, token) => {
return await responseCRU(address + endpoint, 'PATCH', body, token) return await responseCRU(address + endpoint, 'PATCH', body, token)
} }
/**
* universal delete method
* @param {string} endpoint - for example `user/{id}/` where {id} is object id
* @param {string} token - token for verify user in API
*/
const _delete = async (endpoint, token) => { const _delete = async (endpoint, token) => {
return await responseGD(address + endpoint, 'DELETE', token) return await responseGD(address + endpoint, 'DELETE', token)
} }
// Utils // Utils
// Fetch methods // Fetch methods
/**
* fetch `get` / `delete` type methods
* @param {string} address - full endpoint address
* @param {string} method - method like `get` / `delete`
* @param {string} token - token for verify user in API
*/
const responseGD = async (address, method, token) => { const responseGD = async (address, method, token) => {
try { try {
const response = await fetch(address, { const response = await fetch(address, {
@ -45,12 +84,22 @@ const responseGD = async (address, method, token) => {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
}) })
return await responseExceptions( await response.json() ) return await responseExceptions(
} catch ( error ) { await response.json(),
response.status
)
} catch (error) {
return { info: error } return { info: error }
} }
} }
/**
* fetch `post` / `put` / `patch` type methods
* @param {string} address - full endpoint address
* @param {string} method - method like `post` / `put` / `patch`
* @param {{}} body - body of request
* @param {string} token - token for verify user session in API
*/
const responseCRU = async (address, method, body, token) => { const responseCRU = async (address, method, body, token) => {
try { try {
const response = await fetch(address, { const response = await fetch(address, {
@ -64,29 +113,55 @@ const responseCRU = async (address, method, body, token) => {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
}) })
return await responseExceptions( await response.json() ) return await responseExceptions(
} catch ( error ) { await response.json(),
response.status
)
} catch (error) {
return { info: error } return { info: error }
} }
} }
const responseExceptions = async ( response ) => { /**
* fetch bonus exceptions ( not blank fields in request / bad requests )
* @param {Response} response
* @param {number} status
*/
const responseExceptions = async (response, status) => {
try { try {
//progressStream( response ) //progressStream( response )
return { if (status > 300) {
response: response, let info = ''
info: 'operation success' Object.keys(response).forEach(element => {
if (element !== 'detail')
info += element + ' - ' + response[element][0]
else
info += response[element]
})
return {
response: response,
info: info
}
} }
} catch { else
return {
response: response,
info: 'operation success'
}
} catch (error) {
return { return {
response: response, response: response,
info: 'operation failed' info: error
} }
} }
} }
// Get CSRF Token // Get CSRF Token
/**
* get cookie method for CSRF verification
* @param {string} name - name of handled cookie
*/
const getCookie = (name) => { const getCookie = (name) => {
if (!document.cookie) { if (!document.cookie) {
return null; return null;
@ -106,7 +181,7 @@ const csrftoken = getCookie('csrftoken')
// Get progress stream // Get progress stream
/** /**
* only use with fetch API in `then` statement * Fetch streaming (use in `then` statement) usefull for get request progress info
* @param response - is a response from fetch * @param response - is a response from fetch
*/ */
export const progressStream = (response) => { export const progressStream = (response) => {
@ -128,14 +203,14 @@ export const progressStream = (response) => {
return return
} }
loaded += value.byteLength loaded += value.byteLength
console.log( loaded / total * 100 ) console.log(loaded / total * 100)
controller.enqueue(value) controller.enqueue(value)
read() read()
}) })
// .catch(error => { .catch(error => {
// console.error(error) console.error(error)
// controller.error(error) controller.error(error)
// }) })
} }
} }
}) })

View File

@ -20,21 +20,17 @@ export const postAuth = (username, password) => async (dispatch) => {
body, body,
AppService.defaultToken AppService.defaultToken
).then( response => { ).then( response => {
try { serviceUser = {
serviceUser = { id: response['response'].user.id,
id: response.user.id, username: response['response'].user.username,
username: response.user.username, email: response['response'].user.email,
email: response.user.email, ip: response['response'].user.ip,
ip: response.user.ip, city: response['response'].user.city,
city: response.user.city, country: response['response'].user.country,
country: response.user.country, token: response['response'].Authorization
token: response.Authorization
}
dispatch(actions.login(serviceUser))
return { error: 'login success' }
} catch {
return { error: 'login failed' }
} }
dispatch(actions.login(serviceUser))
return response
}) })
} }
@ -43,12 +39,8 @@ export const deleteAuth = (token) => async (dispatch) => {
endpoint + 'auth', endpoint + 'auth',
token token
).then( () => { ).then( () => {
try { dispatch(actions.logout())
dispatch(actions.logout()) return response
return { error: 'logout success'}
} catch {
return { error: 'logout failed' }
}
}) })
} }
@ -71,15 +63,15 @@ export const updateUser = (user, id, token) => async (dispatch) => {
token token
).then( response => { ).then( response => {
serviceUser = { serviceUser = {
id: response.user.id, id: response['response'].user.id,
username: response.user.username, username: response['response'].user.username,
email: response.user.email, email: response['response'].user.email,
ip: response.user.ip, ip: response['response'].user.ip,
city: response.user.city, city: response['response'].user.city,
country: response.user.country, country: response['response'].user.country,
token: token token: response['response'].Authorization
} }
dispatch(actions.login(serviceUser)) dispatch(actions.login( serviceUser ))
return response return response
}) })
} }