vuex-assert
vuex-assert copied to clipboard
Assertion for Vuex state
vuex-assert
Assertion for Vuex state
Examples
Just add assertions into your Vuex modules.
// modules/users.js
import {
boolean,
number,
string,
object,
array
} from 'vuex-assert'
export default {
state: {
isLoading: false,
error: null,
users: []
},
assertions: {
isLoading: boolean,
error: object({
code: number,
message: string
}).optional,
users: array(object({
id: number.assert(id => id > 0, 'id should be unsigned'),
name: string
}))
},
// ... module getters, actions and mutations ...
}
Add assertPlugin to plugins option of Vuex.Store with your modules.
import Vuex from 'vuex'
import modules from './modules'
import { assertPlugin } from 'vuex-assert'
const store = new Vuex.Store({
modules,
plugins: [
assertPlugin({ modules })
]
})
Then, the store state will be validated for every mutation. Like following message will be printed if the assertion is failed.
state.users.error.code == null
number is expected
API
-
class Assertion
-
optional: AssertionGet assertion for optional type of this assertion.
-
assert(fn: (value: any) => boolean, message?: string): AssertionInclude additional assertion for this assertion.
-
-
assertPlugin(options): VuexPluginCreate Vuex plugin with options.
options.assertions: { [key: string]: Assertion }options.modules: { [key: string]: VuexModule }
-
assert(fn: (value: any) => boolean, message?: string): AssertionCreate new assertion.
-
number: AssertionAssertion for number.
-
string: AssertionAssertion for string.
-
boolean: AssertionAssertion for boolean.
-
optional: AssertionAssertion for null or undefined.
-
object(assertions?: { [key: string]: Assertion }, message?: string): AssertionCreate assertion for object with properties assertions.
-
array(assertion?: Assertion, message?: string): AssertionCreate assertion for array with items assertions.
-
and(assertions: Assertion[]): AssertionIntersect given assertions.
-
or(assertions: Assertion[]): AssertionUnion given assertions.
License
MIT