Created
December 26, 2019 16:17
-
-
Save sebassdc/691703bb67c8a74296014dfbba752f58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Yup from 'yup' | |
import { handleErrorCode } from './auth' | |
import { makeRequest } from '../services/requests' | |
import getCurrentPosition from '../../utils/getCurrentPosition' | |
import log from '../../utils/log' | |
const requestSchema = Yup.object().shape( { | |
endpoint: Yup.string().required(), | |
method: Yup.string().default( 'GET' ), | |
query: Yup.object().default( {} ), | |
dispatch: Yup.object().required(), | |
startAction: Yup.object(), | |
successAction: Yup.object().required(), | |
failureAction: Yup.object().required(), | |
withLocation: Yup.bool().default( false ), | |
logResponse: Yup.bool().default( false ), | |
onSuccessHook: Yup.object().default( () => ( () => {} ) ), | |
} ) | |
export const makeRequestWithActions = async ( requestData ) => { | |
let validData | |
try { | |
validData = await requestSchema.validate( requestData ) | |
} catch ( error ) { | |
log( 'thunks/requests > Object passed to makeRequestWithActions is invalid', requestData ) | |
return | |
} | |
const { | |
endpoint, | |
method, | |
query, | |
dispatch, | |
startAction, | |
successAction, | |
failureAction, | |
withLocation, | |
logResponse, | |
onSuccessHook, | |
} = validData | |
try { | |
if ( startAction ) { | |
dispatch( startAction() ) | |
} | |
const { coords, ...otherParams } = query | |
let queryParams = otherParams | |
if ( withLocation ) { | |
const location = coords ? query : await getCurrentPosition() | |
queryParams = { | |
...queryParams, | |
lat: location.coords.latitude, | |
lng: location.coords.longitude, | |
} | |
} | |
const response = await makeRequest( | |
endpoint, | |
queryParams, | |
method, | |
logResponse, | |
) | |
if ( response && response.code ) { | |
handleErrorCode( response.code, dispatch ) | |
dispatch( failureAction( response ) ) | |
} else { | |
dispatch( successAction( response, queryParams ) ) | |
onSuccessHook( response ) | |
} | |
} catch ( error ) { | |
log( `thunks/requests > ${endpoint} > error`, error ) | |
dispatch( failureAction( error.message ) ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment