Skip to content

Instantly share code, notes, and snippets.

@peerhenry
Created February 22, 2019 12:44
Show Gist options
  • Select an option

  • Save peerhenry/634cf5b8daf712ed692997f3831c85fd to your computer and use it in GitHub Desktop.

Select an option

Save peerhenry/634cf5b8daf712ed692997f3831c85fd to your computer and use it in GitHub Desktop.
infi vuex blogpost refactor 4
const validOption = (options, key) => options && options[key] && typeof options[key] === 'function'
const formatOptions = options => {
let result = { }
result.mapPayload = validOption(options, 'handleError') ? options.mapPayload : (context, payload) => payload
result.formatUrl = validOption(options, 'formatUrl') ? options.formatUrl : (context, payload, url) => url
result.handleResponse = validOption(options, 'handleResponse') ? options.handleResponse : _ => _
result.handleError = validOption(options, 'handleError') ? options.handleError : _ => _
return result
}
function setupApiCall(vuexModule, name, url, call, argOptions) {
const options = formatOptions(argOptions)
const pendingKey = name + 'Pending'
const errorKey = name + 'Error'
const capitalizedName = name.charAt(0).toUpperCase() + name.slice(1)
const pendingMutationKey = 'set' + capitalizedName + 'Pending'
const errorMutationKey = 'set' + capitalizedName + 'Error'
vuexModule.state[pendingKey] = false
vuexModule.state[errorKey] = undefined
vuexModule.getters[pendingKey] = (state) => state[pendingKey]
vuexModule.getters[errorKey] = (state) => state[errorKey]
vuexModule.mutations[pendingMutationKey] = (state, pending) => state[pendingKey] = pending
vuexModule.mutations[errorMutationKey] = (state, error) => state[errorKey] = error
vuexModule.actions[name] = (context, payload) => {
context.commit(pendingMutationKey, true)
context.commit(errorMutationKey, undefined)
const formattedUrl = options.formatUrl(context, payload, url)
const data = options.mapPayload(context, payload)
call(formattedUrl, data).then(
(response) => {
context.commit(pendingMutationKey, false)
options.handleResponse(context, payload, response)
},
(error) => {
context.commit(pendingMutationKey, false)
context.commit(errorMutationKey, error)
options.handleError(context, payload, error)
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment