Created
October 24, 2017 16:32
-
-
Save davestewart/d938ea0b7705e5a66d3f5b9a62232c06 to your computer and use it in GitHub Desktop.
Example of a Vuex service
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 Vue from 'vue' | |
import _ from 'lodash' | |
import { compare, stringify } from 'utils/query' | |
import store from 'app/store' | |
/** | |
* Car loader service | |
* | |
* Removes responsibility of loading cars from the results store | |
* | |
* @property {boolean} loading | |
* @property {string} query | |
* @property {string} lastQuery | |
* | |
* @property {Function} search | |
* @property {Function} load | |
*/ | |
const loader = new Vue({ | |
data () { | |
return { | |
lastQuery: '', | |
lastGoodState: {}, | |
loading: false, | |
} | |
}, | |
computed: { | |
state () { | |
return _.cloneDeep(store.get('parameters/search')) | |
}, | |
query () { | |
return stringify(this.state) | |
}, | |
}, | |
methods: { | |
/** | |
* Search all cars | |
* | |
* @return {Promise.<TResult>} | |
*/ | |
search () { | |
this.loading = true | |
return store | |
.dispatch('results/search') | |
.then(() => { | |
this.loading = false | |
}) | |
}, | |
/** | |
* Load cars based on current query | |
* | |
* @return {*} | |
*/ | |
load () { | |
// new queries, load data | |
if (!compare(this.query, this.lastQuery)) { | |
this.lastQuery = this.query | |
const state = this.state | |
this.loading = true | |
return store | |
.dispatch('results/browse') | |
.then(data => { | |
this.loading = false | |
if (data.results.length) { | |
this.lastGoodState = state | |
} | |
return data | |
}) | |
} | |
// same queries, return existing data | |
const data = _.pick(store.state.results, 'cars', 'pagination') | |
return Promise.resolve(data) | |
}, | |
/** | |
* Go back to the last good state | |
*/ | |
back () { | |
store.set('parameters/search', this.lastGoodState) | |
} | |
} | |
}) | |
window.loader = loader | |
export default loader |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment