UNPKG

1.33 kBJavaScriptView Raw
1/**
2 * Abstract service
3 * @class ApService
4 */
5'use strict'
6
7const { ERROR_SCOPE_NAME } = require('./constants')
8const abind = require('abind')
9const scopeMixin = require('./mixins/scope_mixin')
10
11/** @lends ApService */
12class ApService {
13 constructor (store) {
14 const s = this
15 s.store = store
16 abind(s, { proto: ApService.prototype })
17 }
18
19 /**
20 * Get store values
21 * @param {...string} keys - Keys to dig
22 * @returns {*} - Stored value
23 */
24 get (...keys) {
25 const s = this
26 let { store } = s
27 if (!store) {
28 throw new Error('[ApService] store missing')
29 }
30 let state = store.getState()
31 return keys
32 .filter((key) => typeof key !== 'undefined')
33 .reduce((state = {}, key) => state[ key ], state)
34 }
35
36 /**
37 * Dispatch an action
38 * @param {string} actionType - Action type to dispatch
39 * @param {string} fieldName - Field name to dispath
40 * @param {*} value - Value to dispatch
41 * @param {boolean} [isError=false] - Is error or not
42 */
43 dispatch (actionType, fieldName, value, isError = false) {
44 const s = this
45 let { store } = s
46 store.dispatch({
47 type: actionType,
48 meta: { field: fieldName },
49 payload: value,
50 error: isError
51 })
52 }
53}
54
55Object.assign(ApService, { ERROR_SCOPE_NAME })
56
57module.exports = scopeMixin(ApService)