Browse Source

feat: add Store#hasModule(path) API (#834)

* add Store#hasModule(path) API

* fix Store::hasModule(path) return value

* add unit test for Store#hasModule(path)

* Revert "add unit test for Store#hasModule(path)" (reverts commit 09f319705a7d1caead6506f40627e244017d8c0c.)
Add a new test for Store#hasModule()

* fix linting issues
Franck Freiburger 5 years ago
parent
commit
d65d14276e
4 changed files with 33 additions and 0 deletions
  1. 8 0
      src/module/module-collection.js
  2. 4 0
      src/module/module.js
  3. 10 0
      src/store.js
  4. 11 0
      test/unit/modules.spec.js

+ 8 - 0
src/module/module-collection.js

@@ -53,6 +53,14 @@ export default class ModuleCollection {
 
 
     parent.removeChild(key)
     parent.removeChild(key)
   }
   }
+
+  isRegistered (path) {
+    const parent = this.get(path.slice(0, -1))
+    const key = path[path.length - 1]
+
+    return parent.hasChild(key)
+  }
+
 }
 }
 
 
 function update (path, targetModule, newModule) {
 function update (path, targetModule, newModule) {

+ 4 - 0
src/module/module.js

@@ -30,6 +30,10 @@ export default class Module {
     return this._children[key]
     return this._children[key]
   }
   }
 
 
+  hasChild (key) {
+    return key in this._children
+  }
+
   update (rawModule) {
   update (rawModule) {
     this._rawModule.namespaced = rawModule.namespaced
     this._rawModule.namespaced = rawModule.namespaced
     if (rawModule.actions) {
     if (rawModule.actions) {

+ 10 - 0
src/store.js

@@ -215,6 +215,16 @@ export class Store {
     resetStore(this)
     resetStore(this)
   }
   }
 
 
+  hasModule (path) {
+    if (typeof path === 'string') path = [path]
+
+    if (process.env.NODE_ENV !== 'production') {
+      assert(Array.isArray(path), `module path must be a string or an Array.`)
+    }
+
+    return this._modules.isRegistered(path)
+  }
+
   hotUpdate (newOptions) {
   hotUpdate (newOptions) {
     this._modules.update(newOptions)
     this._modules.update(newOptions)
     resetStore(this, true)
     resetStore(this, true)

+ 11 - 0
test/unit/modules.spec.js

@@ -80,6 +80,17 @@ describe('Modules', () => {
       store.commit('a/foo')
       store.commit('a/foo')
       expect(mutationSpy).toHaveBeenCalled()
       expect(mutationSpy).toHaveBeenCalled()
     })
     })
+    it('dynamic module existance test', () => {
+      const store = new Vuex.Store({
+      })
+
+      store.registerModule('bonjour', {
+      })
+
+      expect(store.hasModule('bonjour')).toBe(true)
+      store.unregisterModule('bonjour')
+      expect(store.hasModule('bonjour')).toBe(false)
+    })
 
 
     it('dynamic module registration preserving hydration', () => {
     it('dynamic module registration preserving hydration', () => {
       const store = new Vuex.Store({})
       const store = new Vuex.Store({})