From 13914f428352dcd40b16b27c30788cf728fe8efd Mon Sep 17 00:00:00 2001 From: TBS093A Date: Tue, 11 Aug 2020 20:36:33 +0200 Subject: [PATCH] refactor AppService exceptions && add JSDoc --- .../commands/fetchCommands/Album/Create.js | 4 +- .../commands/fetchCommands/Album/Delete.js | 8 +- .../commands/fetchCommands/Album/GetAll.js | 39 +++--- .../commands/fetchCommands/Album/GetOne.js | 15 ++- .../commands/fetchCommands/Album/Update.js | 8 +- src/stores/AppService.js | 111 +++++++++++++++--- src/stores/user/duck/operations.js | 48 ++++---- 7 files changed, 148 insertions(+), 85 deletions(-) diff --git a/src/components/index/indexConsole/commands/fetchCommands/Album/Create.js b/src/components/index/indexConsole/commands/fetchCommands/Album/Create.js index e24fd7e..85894d1 100644 --- a/src/components/index/indexConsole/commands/fetchCommands/Album/Create.js +++ b/src/components/index/indexConsole/commands/fetchCommands/Album/Create.js @@ -42,7 +42,7 @@ const AlbumCreate = ({ album, user.token ).then( response => { - setMessage( response['info'] ) + setMessage( response['info'] + '\n' ) }) } @@ -81,7 +81,7 @@ const AlbumCreate = ({ titleInput.current.value = '' descriptionInput.current.value = '' - setConsoleHistory( consoleHistory + message + '\n' ) + setConsoleHistory( consoleHistory + message ) setComponentVisible( false ) setImage('') setImageInfo('Drop/Click\nfor upload album image...') diff --git a/src/components/index/indexConsole/commands/fetchCommands/Album/Delete.js b/src/components/index/indexConsole/commands/fetchCommands/Album/Delete.js index f535f99..b91e4e4 100644 --- a/src/components/index/indexConsole/commands/fetchCommands/Album/Delete.js +++ b/src/components/index/indexConsole/commands/fetchCommands/Album/Delete.js @@ -25,11 +25,7 @@ const AlbumDelete = ({ id, user.token ).then( response => { - if ( response.detail !== 'Not found.' ){ - setMessage('album delete success') - } else{ - setMessage('album delete failed') - } + setMessage( response['info'] + '\n' ) }) } } @@ -45,7 +41,7 @@ const AlbumDelete = ({ idInput.current.value = '' - setConsoleHistory( consoleHistory + message + '\n' ) + setConsoleHistory( consoleHistory + message ) setComponentVisible( false ) setMessage('') } diff --git a/src/components/index/indexConsole/commands/fetchCommands/Album/GetAll.js b/src/components/index/indexConsole/commands/fetchCommands/Album/GetAll.js index 3b4a24d..9bd3a38 100644 --- a/src/components/index/indexConsole/commands/fetchCommands/Album/GetAll.js +++ b/src/components/index/indexConsole/commands/fetchCommands/Album/GetAll.js @@ -13,45 +13,44 @@ const AlbumGetAll = ({ }) => { const [message, setMessage] = useState('') - const [oneRequest, setOne ] = useState(false) + const [oneRequest, setOne] = useState(false) useEffect( () => { if (componentVisible && oneRequest === false) { - getAllAlbum() - .then( response => { - setMessage( - mapAlbumsToString( response['response'] ) - + response['info'] - ) - console.log( response ) - }) - setOne( !oneRequest ) + getAllAlbum().then(response => { + setMessage( + mapAlbumsToString( + response['response'] + ) + response['info'] + '\n' + ) + }) + setOne(!oneRequest) } else { activateConsoleInput() } - if ( message !== '' ) { + if (message !== '') { setConsoleHistory(consoleHistory + message) setComponentVisible(false) - setOne( !oneRequest ) + setOne(!oneRequest) setMessage('') - } + } } ) const mapAlbumsToString = (albums) => { let list = '.albums\n' for (let i = 0; i < albums.length; i++) { - if ( i !== albums.length - 1 ) + if (i !== albums.length - 1) list += '├── ' + albums[i].title + '\n' - + '│ ├── id: ' + albums[i].id + '\n' - + '│ ├── user id: ' + albums[i].user_id + '\n' - + '│ └── url: ' + albums[i].url_code + '\n' + + '│ ├── id: ' + albums[i].id + '\n' + + '│ ├── user id: ' + albums[i].user_id + '\n' + + '│ └── url: ' + albums[i].url_code + '\n' else list += '└── ' + albums[i].title + '\n' - + ' ├── id: ' + albums[i].id + '\n' - + ' ├── user id: ' + albums[i].user_id + '\n' - + ' └── url: ' + albums[i].url_code + '\n' + + ' ├── id: ' + albums[i].id + '\n' + + ' ├── user id: ' + albums[i].user_id + '\n' + + ' └── url: ' + albums[i].url_code + '\n' } return list } diff --git a/src/components/index/indexConsole/commands/fetchCommands/Album/GetOne.js b/src/components/index/indexConsole/commands/fetchCommands/Album/GetOne.js index 140ddcf..1f1c08c 100644 --- a/src/components/index/indexConsole/commands/fetchCommands/Album/GetOne.js +++ b/src/components/index/indexConsole/commands/fetchCommands/Album/GetOne.js @@ -22,15 +22,18 @@ const AlbumGetOne = ({ setConsoleHistory( consoleHistory + 'album id: ' + inputValue + '\n') if ( inputValue >= 0 ) { getOneAlbum( inputValue ).then( response => { - if ( response.detail !== 'Not found.' ){ + if ( response['info'] !== 'Not found.' ){ setMessage( - response.title + '\n' - + '├── id: ' + response.id + '\n' - + '├── user id: ' + response.user_id + '\n' - + '└── url: ' + response.url_code + '\n' + response['response'].title + '\n' + + '├── id: ' + response['response'].id + '\n' + + '├── user id: ' + response['response'].user_id + '\n' + + '└── url: ' + response['response'].url_code + '\n' + + response['info'] + '\n' ) } else{ - setMessage('album not found') + setMessage( + response['info'] + '\n' + ) } }) } diff --git a/src/components/index/indexConsole/commands/fetchCommands/Album/Update.js b/src/components/index/indexConsole/commands/fetchCommands/Album/Update.js index 439179a..aae2a2a 100644 --- a/src/components/index/indexConsole/commands/fetchCommands/Album/Update.js +++ b/src/components/index/indexConsole/commands/fetchCommands/Album/Update.js @@ -50,10 +50,8 @@ const AlbumUpdate = ({ id, album, user.token - ).then( () => { - setMessage('album update success') - }).catch( () => { - setMessage('album update failed') + ).then( response => { + setMessage( response['info'] + '\n' ) }) } @@ -71,7 +69,7 @@ const AlbumUpdate = ({ descriptionInput.current.value = '' imageInput.current.value = '' - setConsoleHistory( consoleHistory + message + '\n' ) + setConsoleHistory( consoleHistory + message ) setComponentVisible( false ) setMessage('') } diff --git a/src/stores/AppService.js b/src/stores/AppService.js index 0d8e951..4ef9a39 100644 --- a/src/stores/AppService.js +++ b/src/stores/AppService.js @@ -1,38 +1,77 @@ import { address } from './APIAddress' -// session Token +// User Session Token let defaultToken = 'empty token' + // CRUD methods +/** + * get list method + * @param {string} endpoint - for example `user/` + */ const _getList = async (endpoint) => { return await responseGD(address + endpoint, 'GET', defaultToken) } +/** + * get one row / record + * @param {string} endpoint - for example `user/` + */ const _getOne = async (endpoint) => { 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) => { 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) => { 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) => { 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) => { return await responseGD(address + endpoint, 'DELETE', token) } + // Utils // 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) => { try { const response = await fetch(address, { @@ -45,12 +84,22 @@ const responseGD = async (address, method, token) => { "Content-Type": "application/json" } }) - return await responseExceptions( await response.json() ) - } catch ( error ) { + return await responseExceptions( + await response.json(), + response.status + ) + } catch (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) => { try { const response = await fetch(address, { @@ -64,29 +113,55 @@ const responseCRU = async (address, method, body, token) => { "Content-Type": "application/json" } }) - return await responseExceptions( await response.json() ) - } catch ( error ) { + return await responseExceptions( + await response.json(), + response.status + ) + } catch (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 { //progressStream( response ) - return { - response: response, - info: 'operation success' + if (status > 300) { + let info = '' + Object.keys(response).forEach(element => { + if (element !== 'detail') + info += element + ' - ' + response[element][0] + else + info += response[element] + }) + return { + response: response, + info: info + } } - } catch { - return { + else + return { + response: response, + info: 'operation success' + } + } catch (error) { + return { response: response, - info: 'operation failed' + info: error } } } // Get CSRF Token +/** + * get cookie method for CSRF verification + * @param {string} name - name of handled cookie + */ const getCookie = (name) => { if (!document.cookie) { return null; @@ -106,7 +181,7 @@ const csrftoken = getCookie('csrftoken') // 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 */ export const progressStream = (response) => { @@ -128,14 +203,14 @@ export const progressStream = (response) => { return } loaded += value.byteLength - console.log( loaded / total * 100 ) + console.log(loaded / total * 100) controller.enqueue(value) read() }) - // .catch(error => { - // console.error(error) - // controller.error(error) - // }) + .catch(error => { + console.error(error) + controller.error(error) + }) } } }) diff --git a/src/stores/user/duck/operations.js b/src/stores/user/duck/operations.js index e53762a..ecfa505 100644 --- a/src/stores/user/duck/operations.js +++ b/src/stores/user/duck/operations.js @@ -20,21 +20,17 @@ export const postAuth = (username, password) => async (dispatch) => { body, AppService.defaultToken ).then( response => { - try { - serviceUser = { - id: response.user.id, - username: response.user.username, - email: response.user.email, - ip: response.user.ip, - city: response.user.city, - country: response.user.country, - token: response.Authorization - } - dispatch(actions.login(serviceUser)) - return { error: 'login success' } - } catch { - return { error: 'login failed' } + serviceUser = { + id: response['response'].user.id, + username: response['response'].user.username, + email: response['response'].user.email, + ip: response['response'].user.ip, + city: response['response'].user.city, + country: response['response'].user.country, + token: response['response'].Authorization } + dispatch(actions.login(serviceUser)) + return response }) } @@ -43,12 +39,8 @@ export const deleteAuth = (token) => async (dispatch) => { endpoint + 'auth', token ).then( () => { - try { - dispatch(actions.logout()) - return { error: 'logout success'} - } catch { - return { error: 'logout failed' } - } + dispatch(actions.logout()) + return response }) } @@ -71,15 +63,15 @@ export const updateUser = (user, id, token) => async (dispatch) => { token ).then( response => { serviceUser = { - id: response.user.id, - username: response.user.username, - email: response.user.email, - ip: response.user.ip, - city: response.user.city, - country: response.user.country, - token: token + id: response['response'].user.id, + username: response['response'].user.username, + email: response['response'].user.email, + ip: response['response'].user.ip, + city: response['response'].user.city, + country: response['response'].user.country, + token: response['response'].Authorization } - dispatch(actions.login(serviceUser)) + dispatch(actions.login( serviceUser )) return response }) }