Skip to content

Instantly share code, notes, and snippets.

@kamaladenalhomsi
Created January 14, 2021 08:32
Show Gist options
  • Save kamaladenalhomsi/6de343ca885e308d9cc58c4fe65b1351 to your computer and use it in GitHub Desktop.
Save kamaladenalhomsi/6de343ca885e308d9cc58c4fe65b1351 to your computer and use it in GitHub Desktop.
ViewState.js
import { isFunction } from './helpers'
const GET_KEY = 'get'
const PUSH_KEY = 'PUSH_TO_'
const SET_KEY = 'SET_'
function mergeWithViewState (state, payload) {
Object.keys(payload).forEach(key => {
state[key] = payload[key]
})
}
function defineViewState (schema) {
let viewState = {}
Object.keys(schema).forEach(key => {
viewState[key] = {
data: schema[key].default || [],
loaded: false
}
})
return viewState
}
function defineViewMutations (schema) {
let viewMutations = {}
Object.keys(schema).forEach(key => {
viewMutations[SET_KEY + key.toUpperCase()] = (state, payload) => mergeWithViewState(state[key], payload)
viewMutations[PUSH_KEY + key.toUpperCase()] = (state, data) => {
if (Array.isArray(data)) {
state[key].data.push(...data)
} else {
state[key].data.push(data)
}
}
})
return viewMutations
}
function defineViewActions (schema) {
let viewActions = {}
Object.keys(schema).forEach(key => {
const resource = schema[key]
const keyWithFirstLetterUppercase = key[0].toUpperCase() + key.slice(1, key.length)
viewActions[GET_KEY + keyWithFirstLetterUppercase] = function (context, payload = {}) {
const setKey = SET_KEY + key.toUpperCase()
const pushKey = PUSH_KEY + key.toUpperCase()
if (!context.state[key].loaded) {
if (isFunction(resource.params)) {
payload = {
...payload,
...resource.params(context)
}
}
const query = resource.query(payload)
context.commit(setKey, {
loaded: false
})
query.then(data => {
context.commit(setKey, {
loaded: true
})
if (resource.paginated) {
if (payload.per_page * payload.page > context.state[key].data.length) {
context.commit(pushKey, data)
}
} else {
context.commit(setKey, {
data
})
}
if (isFunction(payload.callback)) {
payload.callback(data)
}
})
}
}
})
return viewActions
}
export function defineViews (schema) {
return {
state: defineViewState(schema),
mutations: defineViewMutations(schema),
actions: defineViewActions(schema)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment