1
0
mirror of synced 2024-11-29 08:36:12 +03:00
vue-formulario/src/store.js

94 lines
2.6 KiB
JavaScript
Raw Normal View History

2018-01-31 01:21:21 +03:00
import {map, reduce} from './utils'
/**
* Curried function for creating the formState
* @param {Object} options
*/
export const formulateState = (options = {}) => () => Object.assign({
values: {},
errors: {},
validationErrors: {},
meta: {}
2018-01-31 01:21:21 +03:00
}, options)
/**
* Function for creating the formGetters
* @param {string} module
* @param {Object} getters
*/
export const formulateGetters = (moduleName = '', getters = {}) => Object.assign({
formValues (state) {
return state.values
},
formErrors (state) {
return state.errors
},
formValidationErrors (state) {
return state.validationErrors
},
formMeta (state) {
return reduce(state.meta, (forms, form, fields) => {
forms[form] = reduce(fields, (arr, field, data) => arr.concat(data), [])
return forms
}, {})
},
2018-01-31 01:21:21 +03:00
hasErrors (state) {
return map(state.errors, (form, errors) => {
return reduce(errors, (hasErrors, field, errors) => hasErrors || !!errors.length, false)
})
},
hasValidationErrors (state) {
return map(state.validationErrors, (form, errors) => {
return reduce(errors, (hasErrors, field, errors) => hasErrors || !!errors.length, false)
})
2018-01-31 01:21:21 +03:00
}
}, getters)
/**
* Function for creating the formActions
* @param {string} moduleName
* @param {Object} actions
*/
export const formulateActions = (moduleName = '', actions = {}) => Object.assign({
}, actions)
/**
* Function for creating the formMutations
* @param {Object} mutations
*/
export const formulateMutations = (mutations = {}) => Object.assign({
setFieldValue (state, {form, field, value}) {
state.values = Object.assign({}, state.values, {
[form]: Object.assign({}, state.values[form] || {}, {[field]: value})
})
},
setFieldErrors (state, {form, field, errors}) {
state.errors = Object.assign({}, state.errors, {
[form]: Object.assign({}, state.errors[form] || {}, {[field]: errors})
})
},
setFieldValidationErrors (state, {form, field, errors}) {
state.validationErrors = Object.assign({}, state.validationErrors, {
[form]: Object.assign({}, state.validationErrors[form] || {}, {[field]: errors})
})
},
setFieldMeta (state, {form, field, data}) {
state.meta = Object.assign({}, state.meta, {
[form]: Object.assign({}, state.meta[form] || {}, {[field]: data})
})
2018-01-31 01:21:21 +03:00
}
}, mutations)
/**
* Function for exposing a full vuex module.
* @param {string} moduleName
* @param {Object} validation
*/
export const formulateModule = (moduleName) => ({
state: formulateState(),
getters: formulateGetters(moduleName),
actions: formulateActions(moduleName),
mutations: formulateMutations(),
namespaced: true
2018-01-31 01:21:21 +03:00
})