Nuxt/lib/app/store.js

71 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-12-25 20:16:30 +00:00
import Vue from 'vue'
import Vuex from 'vuex'
2017-05-13 17:32:11 +00:00
2016-12-25 20:16:30 +00:00
Vue.use(Vuex)
// Recursive find files in {srcDir}/store
const files = require.context('@/store', true, /^\.\/.*\.(js|ts)$/)
2017-05-13 17:32:11 +00:00
const filenames = files.keys()
// Store
let storeData = {}
// Check if store/index.js exists
2017-05-20 09:36:35 +00:00
const indexFilename = filenames.find((filename) => filename.includes('./index.'))
if (indexFilename) {
storeData = getModule(indexFilename)
2017-05-13 17:32:11 +00:00
}
2017-05-21 00:03:32 +00:00
// If store is not an exported method = modules store
if (typeof storeData !== 'function') {
// Store modules
if (!storeData.modules) {
storeData.modules = {}
}
2017-01-02 09:13:53 +00:00
2017-05-21 00:03:32 +00:00
for (let filename of filenames) {
let name = filename.replace(/^\.\//, '').replace(/\.(js|ts)$/, '')
if (name === 'index') continue
2017-05-13 17:32:11 +00:00
2017-05-21 00:03:32 +00:00
let namePath = name.split(/\//)
let module = getModuleNamespace(storeData, namePath)
name = namePath.pop()
module[name] = getModule(filename)
module[name].namespaced = true
}
2017-05-13 17:32:11 +00:00
}
// createStore
export const createStore = storeData instanceof Function ? storeData : () => {
return new Vuex.Store(Object.assign({}, storeData, {
state: storeData.state instanceof Function ? storeData.state() : {}
}))
2017-05-13 17:45:42 +00:00
}
2017-05-13 17:32:11 +00:00
// Dynamically require module
function getModule (filename) {
2017-05-13 17:32:11 +00:00
const file = files(filename)
2017-05-13 17:45:42 +00:00
const module = file.default || file
2017-05-13 17:32:11 +00:00
if (module.commit) {
2017-05-22 12:26:24 +00:00
throw new Error('[nuxt] store/' + filename.replace('./', '') + ' should export a method which returns a Vuex instance.')
}
if (module.state && typeof module.state !== 'function') {
throw new Error('[nuxt] state should be a function in store/' + filename.replace('./', ''))
2017-05-13 17:32:11 +00:00
}
return module
2016-12-26 16:19:10 +00:00
}
function getModuleNamespace (storeData, namePath) {
2017-03-28 14:28:24 +00:00
if (namePath.length === 1) {
return storeData.modules
}
let namespace = namePath.shift()
storeData.modules[namespace] = storeData.modules[namespace] || {}
storeData.modules[namespace].namespaced = true
storeData.modules[namespace].modules = storeData.modules[namespace].modules || {}
return getModuleNamespace(storeData.modules[namespace], namePath)
}