Skip to content

Commit 71a47dc

Browse files
authored
Update service-plugin.md
remove <2.0.0 stuff, standardize state & configuration
1 parent 6c307fb commit 71a47dc

File tree

1 file changed

+121
-107
lines changed

1 file changed

+121
-107
lines changed

docs/service-plugin.md

Lines changed: 121 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -3,55 +3,101 @@ title: Service Plugin
33
sidebarDepth: 3
44
---
55

6+
# Service Plugin
7+
68
<!-- markdownlint-disable MD002 MD033 MD041 -->
79

810
The `makeServicePlugin` method creates a vuex plugin which connects a Feathers service to the Vuex store. Once you create a plugin, you must register it in the Vuex store's `plugins` section.
911

10-
See the [setup documentation](/api-overview.html#service-plugins) to learn the basics of setting up a Service Plugin.
12+
## Setup
13+
14+
See the [setup documentation](./getting-started.html#service-plugins) to learn the basics of setting up a Service Plugin.
1115

1216
## Configuration
1317

14-
The following options are supported on `makeServicePlugin`.
18+
The following options are supported on `makeServicePlugin`:
1519

1620
```js
17-
{
18-
idField: '_id', // The field in each record that will contain the id
19-
nameStyle: 'path', // Use the full service path as the Vuex module name, instead of just the last section
20-
namespace: 'custom-namespace', // Customize the Vuex module name. Overrides nameStyle.
21-
debug: true, // Enable some logging for debugging
22-
servicePath: '', // Not all Feathers service plugins expose the service path, so it can be manually specified when missing.
23-
instanceDefaults: () => ({}), // Override this method to provide default data for new instances. If using Model classes, specify this as a static class property.
24-
setupInstance: instance => instance, // Override this method to setup data types or related data on an instance. If using Model classes, specify this as a static class property.
25-
autoRemove: true, // Automatically remove records missing from responses (only use with feathers-rest)
26-
enableEvents: false, // Turn off socket event listeners. It's true by default
21+
import Model from "../users.model";
22+
23+
const servicePath = 'users'
24+
const servicePlugin = makeServicePlugin({
25+
// necesarry
26+
Model,
27+
service: feathersClient.service(servicePath),
28+
29+
// optional
30+
servicePath,
31+
idField: 'id',
32+
tempIdField: '__id',
33+
servicePath: '',
34+
nameStyle: 'short',
35+
debug: false,
36+
autoRemove: false,
37+
preferUpdate: false,
38+
enableEvents: true,
39+
addOnUpsert: false,
40+
replaceItems: false,
41+
skipRequestIfExists: false,
42+
43+
namespace: null,
44+
modelName: 'User',
45+
46+
instanceDefaults: () => ({}),
47+
setupInstance: instance => instance,
2748
handleEvents: {
28-
created: (item, { model, models }) => options.enableEvents, // handle `created` events, return true to add to the store
29-
patched: (item, { model, models }) => options.enableEvents, // handle `created` events, return true to update in the store
30-
updated: (item, { model, models }) => options.enableEvents, // handle `created` events, return true to update in the store
31-
removed: (item, { model, models }) => options.enableEvents // handle `removed` events, return true to remove from the store
49+
created: (item, { model, models }) => options.enableEvents,
50+
patched: (item, { model, models }) => options.enableEvents,
51+
updated: (item, { model, models }) => options.enableEvents,
52+
removed: (item, { model, models }) => options.enableEvents
3253
},
33-
addOnUpsert: true, // Add new records pushed by 'updated/patched' socketio events into store, instead of discarding them. It's false by default
34-
replaceItems: true, // If true, updates & patches replace the record in the store. Default is false, which merges in changes
35-
skipRequestIfExists: true, // For get action, if the record already exists in store, skip the remote request. It's false by default
36-
modelName: 'OldTask' // Default modelName would have been 'Task'
37-
}
54+
55+
state: {},
56+
getters: {},
57+
mutations: {},
58+
actions: {},
59+
60+
//...
61+
});
3862
```
63+
The following options can also be configured in [Global Configuration](getting-started.html#global-configuration) for every service initialized using `feathers-client.js`:
64+
65+
- `idField {String}` - **Default:** `'id'` - The field in each record that will contain the id
66+
- `tempIdField {Boolean}` - **Default:** `'__id'` - The field in each temporary record that contains the id
67+
- `debug {Boolean}` - **Default:** `false` - Enable some logging for debugging
68+
- `autoRemove {Boolean}` - **Default:** `false` - If `true` automatically remove records missing from responses (only use with feathers-rest)
69+
- `addOnUpsert {Boolean}` - **Default:** `false` - If `true` add new records pushed by 'updated/patched' socketio events into store, instead of discarding them.
70+
- `replaceItems {Boolean}` - **Default:** `false` - If `true`, updates & patches replace the record in the store. Default is false, which merges in changes.
71+
- `skipRequestIfExists {Boolean}` - **Default:** `false` - For get action, if `true` the record already exists in store, skip the remote request.
72+
- `preferUpdate {Boolean}` - **Default:** `false` - If `true`, calling `model.save()` will do an `update` instead of a `patch`.
73+
- `enableEvents {Boolean}` - **Default:** `true` - If `false` socket event listeners will be turned off
74+
- `nameStyle {'short'|'path'}` - **Default:** `'short'` - Use the full service path as the Vuex module name, instead of just the last section.
75+
76+
The following options can only configured individually per service plugin
77+
78+
- `servicePath {String}`- Not all Feathers service plugins expose the service path, so it can be manually specified when missing.
79+
- `namespace {String}`, - **Default:** `nameStyle === 'short' ? ${afterLastSlashOfServicePath} : ${stripSlashesFromServicePath}` - Customize the Vuex module name. Overrides nameStyle.
80+
- `modelName {String}` - **Default:** `${ServicePlugin.Model.modelName}`
81+
- `instanceDefaults {Function}` - **Default:** `() => ({})` - Override this method to provide default data for new instances. If using Model classes, specify this as a static class property.
82+
- `setupInstance {Function}` **Default:** `instance => instance` - Override this method to setup data types or related data on an instance. If using Model classes, specify this as a static class property.
83+
- `handleEvents {Object}`
84+
- `created {Function}` - **Default:** `(item, { model, models }) => options.enableEvents` - handle `created` events, return true to add to the store
85+
- `patched {Function}` - **Default:** `(item, { model, models }) => options.enableEvents` - handle `created` events, return true to update in the store
86+
- `updated {Function}` - **Default:** `(item, { model, models }) => options.enableEvents` - handle `created` events, return true to update in the store
87+
- `removed {Function}` - **Default:** `(item, { model, models }) => options.enableEvents` - handle `removed` events, return true to remove from the store
88+
89+
- `state {Object}` - **Default:**: `null` - Pass custom `states` to the service plugin or modify existing ones
90+
- `getters {Object}` - **Default:** `null` - Pass custom `getters` to the service plugin or modify existing ones
91+
- `mutations {Object}` - **Default:** `null` - Pass custom `mutations` to the service plugin or modify existing ones
92+
- `actions {Object}` - **Default:** `null` - Pass custom `actions` to the service plugin or modify existing ones
3993

4094
## Realtime by Default
4195

4296
Service plugins automatically listen to all socket messages received by the Feathers Client. This can be disabled by setting `enableEvents: false` in the options, as shown above.
4397

44-
## New in Feathers-Vuex 2.0
45-
46-
Feathers-Vuex 2.0 includes a few breaking changes to the service plugin. Some of these changes are being made to prepare for future compatibility beyond FeathersJS
47-
48-
- The `service` method is now called `makeServicePlugin`
49-
- The Feathers Client service is no longer created, internally, so a Feathers service object must be provided instead of just the path string.
50-
- A Model class is now required. The `instanceDefaults` API has been moved into the Model class. You can find a basic example of a minimal Model class in the [Data Modeling](/model-classes.html) docs.
51-
5298
## The FeathersClient Service
5399

54-
Once the service plugin has been registered with Vuex, the FeathersClient Service will have a new `service.FeathersVuexModel` property. This provides access to the service's [Model class](./model-classes.md).
100+
Once the service plugin has been registered with Vuex, the FeathersClient Service will have a new `service.FeathersVuexModel` property. This provides access to the service's [Model class](./model-classes.html).
55101

56102
```js
57103
import { models } from 'feathers-vuex'
@@ -66,15 +112,30 @@ Each service comes loaded with the following default state:
66112
```js
67113
{
68114
ids: [],
69-
keyedById: {}, // A hash map, keyed by id of each item
70115
idField: 'id',
71-
servicePath: 'v1/todos' // The full service path
72-
autoRemove: false, // Indicates that this service will not automatically remove results missing from subsequent requests.
73-
replaceItems: false, // When set to true, updates and patches will replace the record in the store instead of merging changes
74-
paginate: false, // Indicates if pagination is enabled on the Feathers service.
75-
76-
paramsForServer: [], // Custom query operators that are ignored in the find getter, but will pass through to the server.
77-
whitelist: [], // Custom query operators that will be allowed in the find getter.
116+
keyedById: {},
117+
tempsById: {},
118+
tempsByNewId: {},
119+
pagination: {
120+
defaultLimit: null,
121+
defaultSkip: null
122+
},
123+
servicePath: 'v1/todos'
124+
modelName: 'Todo',
125+
autoRemove: false,
126+
replaceItems: false,
127+
128+
pagination: {
129+
ids: []
130+
limit: 0
131+
skip: 0
132+
ip: 0
133+
total: 0,
134+
mostRecent: any
135+
},
136+
137+
paramsForServer: [],
138+
whitelist: [],
78139

79140
isFindPending: false,
80141
isGetPending: false,
@@ -92,25 +153,29 @@ Each service comes loaded with the following default state:
92153
}
93154
```
94155

95-
The following attributes are available in each service module's state:
96-
97156
- `ids {Array}` - an array of plain ids representing the ids that belong to each object in the `keyedById` map.
157+
- `idField {String}` - the name of the field that holds each item's id. *Default: `'id'`*
98158
- `keyedById {Object}` - a hash map keyed by the id of each item.
159+
- `tempsById {Object}` - a hash map of temporary records, [keyed by tempIdField](./getting-started.html#global-configuration) of each item
160+
- `tempsByNewId {Object}` - temporary storage for temps while getting transferred from tempsById to keyedById
99161
- `servicePath {String}` - the full service path, even if you alias the namespace to something else.
100162
- `modelName {String}` - the key in the $FeathersVuex plugin where the model will be found.
101-
- `autoRemove {Boolean` - indicates that this service will not automatically remove results missing from subsequent requests. Only use with feathers-rest. Default is false.
163+
- `autoRemove {Boolean}` - indicates that this service will not automatically remove results missing from subsequent requests. Only use with feathers-rest. Default is false.
102164
- `replaceItems {Boolean}` - When set to true, updates and patches will replace the record in the store instead of merging changes. Default is false
103-
- `idField {String}` - the name of the field that holds each item's id. *Default: `'id'`*
104-
- `paginate {Boolean}` - Indicates if the service has pagination turned on.
165+
166+
- `pagination {Object}` - provides informaiton about the last made queries
167+
168+
- `paramsForServer {Array}` - Custom query operators that are ignored in the find getter, but will pass through to the server.
169+
- `whitelist {Array}` - Custom query operators that will be allowed in the find getter.
105170

106171
The following state attributes allow you to bind to the pending state of requests:
107172

108-
- `isFindPending {Boolean}` - `true` if there's a pending `find` request. `false` if not.
109-
- `isGetPending {Boolean}` - `true` if there's a pending `get` request. `false` if not.
110-
- `isCreatePending {Boolean}` - `true` if there's a pending `create` request. `false` if not.
111-
- `isUpdatePending {Boolean}` - `true` if there's a pending `update` request. `false` if not.
112-
- `isPatchPending {Boolean}` - `true` if there's a pending `patch` request. `false` if not.
113-
- `isRemovePending {Boolean}` - `true` if there's a pending `remove` request. `false` if not.
173+
- `isFindPending {Boolean}` - `true` if there's a pending `find` request. `false` if not.
174+
- `isGetPending {Boolean}` - `true` if there's a pending `get` request. `false` if not.
175+
- `isCreatePending {Boolean}` - `true` if there's a pending `create` request. `false` if not.
176+
- `isUpdatePending {Boolean}` - `true` if there's a pending `update` request. `false` if not.
177+
- `isPatchPending {Boolean}` - `true` if there's a pending `patch` request. `false` if not.
178+
- `isRemovePending {Boolean}` - `true` if there's a pending `remove` request. `false` if not.
114179

115180
The following state attribute will be populated with any request error, serialized as a plain object:
116181

@@ -173,12 +238,6 @@ Removes the passed in items or ids from the store.
173238

174239
- `items {Array}` - An array of ids or of objects with ids that will be removed from the data store.
175240

176-
### `clearList(state)`
177-
178-
> Removed in 2.0
179-
180-
Clears the `list`, excepting the `current` item.
181-
182241
### `clearAll(state)`
183242

184243
Clears all data from `ids`, `keyedById`, and `currentId`
@@ -187,47 +246,13 @@ Clears all data from `ids`, `keyedById`, and `currentId`
187246

188247
The following mutations are called automatically by the service actions, and will rarely, if ever, need to be used manually.
189248

190-
Before Feathers-Vuex 2.0, these were the available mutations:
191-
192-
- `setFindPending(state)` - sets `isFindPending` to `true`
193-
- `unsetFindPending(state)` - sets `isFindPending` to `false`
194-
- `setGetPending(state)` - sets `isGetPending` to `true`
195-
- `unsetGetPending(state)` - sets `isGetPending` to `false`
196-
- `setCreatePending(state)` - sets `isCreatePending` to `true`
197-
- `unsetCreatePending(state)` - sets `isCreatePending` to `false`
198-
- `setUpdatePending(state)` - sets `isUpdatePending` to `true`
199-
- `unsetUpdatePending(state)` - sets `isUpdatePending` to `false`
200-
- `setPatchPending(state)` - sets `isPatchPending` to `true`
201-
- `unsetPatchPending(state)` - sets `isPatchPending` to `false`
202-
- `setRemovePending(state)` - sets `isRemovePending` to `true`
203-
- `unsetRemovePending(state)` - sets `isRemovePending` to `false`
204-
205-
In Feathers-Vuex 2.0, these have changed to only two mutations:
206-
207249
- `setPending(state, method)` - sets the `is${method}Pending` attribute to true
208250
- `unsetPending(state, method)` - sets the `is${method}Pending` attribute to false
209251

210252
### Mutations for Managing Errors
211253

212254
The following mutations are called automatically by the service actions, and will rarely need to be used manually.
213255

214-
Before Feathers-Vuex 2.0, these were the available mutations:
215-
216-
- `setFindError(state, error)`
217-
- `clearFindError(state)`
218-
- `setGetError(state, error)`
219-
- `clearGetError(state)`
220-
- `setCreateError(state, error)`
221-
- `clearCreateError(state)`
222-
- `setUpdateError(state, error)`
223-
- `clearUpdateError(state)`
224-
- `setPatchError(state, error)`
225-
- `clearPatchError(state)`
226-
- `setRemoveError(state, error)`
227-
- `clearRemoveError(state)`
228-
229-
In Feathers-Vuex 2.0, these have changed to only two mutations:
230-
231256
- `setError(state, { method, error })` - sets the `errorOn${method}` attribute to the error
232257
- `clearError(state, method)` - sets the `errorOn${method}` attribute to `null`
233258

@@ -254,7 +279,7 @@ See the section about pagination, below, for more information that is applicable
254279

255280
### `afterFind(response)`
256281

257-
The `afterFind` action is called by the `find` action after a successful response is added to the store. It is called with the current response. By default, it is a no-op (it literally does nothing), and is just a placeholder for you to use when necessary. See the sections on [customizing the default store](#Customizing-a-Service’s-Default-Store) and [Handling custom server responses](./common-patterns.md#Handling-custom-server-responses) for example usage.
282+
The `afterFind` action is called by the `find` action after a successful response is added to the store. It is called with the current response. By default, it is a no-op (it literally does nothing), and is just a placeholder for you to use when necessary. See the sections on [customizing the default store](#Customizing-a-Service’s-Default-Store) and [Handling custom server responses](./common-patterns.html#Handling-custom-server-responses) for example usage.
258283

259284
### `get(id)` or `get([id, params])`
260285

@@ -583,7 +608,7 @@ In summary, any time a query param other than `$limit` and `$skip` changes, we g
583608

584609
Now that we've reviewed how pagination tracking works under the hood, you might be asking "Why?" There are a few reasons:
585610

586-
1. Improve performance with cacheing. It's now possible to skip making a query if we already have valid data for the current query. The [`makeFindMixin`](./mixins.md) mixin makes this very easy with its built-in `queryWhen` feature.
611+
1. Improve performance with cacheing. It's now possible to skip making a query if we already have valid data for the current query. The [`makeFindMixin`](./mixins.html) mixin makes this very easy with its built-in `queryWhen` feature.
587612
2. Allow fall-through cacheing of paginated data. A common challenge occurs when you provide the same query params to the `find` action and the `find` getter. As you'll learn in the next section, the `find` getter allows you to make queries against the Vuex store as though it were a Feathers database adapter. But what happens when you pass `{ $limit: 10, $skip: 10 }` to the action and getter?<br/>
588613
First, lets review what happens with the `find` action. The database is aware of all 155 records, so it skips the first 10 and returns the next 10 records. Those records get populated in the store, so the store now has 10 records. Now we pass the query to the `find` getter and tell it to `$skip: 10`. It skips the only 10 records that are in the store and returns an empty array! That's definitely not what we wanted.<br/>
589614
Since we're now storing this pagination structure, we can build a utility around the `find` getter which will allow us to return the same data with the same query. The data is still reactive and will automatically update when a record changes.
@@ -608,7 +633,7 @@ The `find` getter queries data from the local store using the same Feathers quer
608633

609634
## Customizing a Service's Default Store
610635

611-
As shown in the first example, the service module allows you to customize its store:
636+
As shown in the example below, the service module allows you to customize its store:
612637

613638
```js
614639
const store = new Vuex.Store({
@@ -624,30 +649,19 @@ const store = new Vuex.Store({
624649
}
625650
},
626651
mutations: {
627-
setTestToFalse (state) {
628-
state.test = false
652+
setTest (state, val) {
653+
state.test = val;
629654
},
630-
setTestToTrue (state) {
631-
state.test = true
632-
}
633655
},
634656
actions: {
635657
// Overwriting the built-in `afterFind` action.
636658
afterFind ({ commit, dispatch, getters, state }, response) {
637659
// Do something with the response.
638660
// Keep in mind that the data is already in the store.
639661
},
640-
asyncStuff ({ commit, dispatch }, args) {
662+
asyncStuff ({ state, getters, commit, dispatch }, args) {
641663
commit('setTestToTrue')
642-
643-
return doSomethingAsync(id, params)
644-
.then(result => {
645-
commit('setTestToFalse')
646-
return dispatch('otherAsyncStuff', result)
647-
})
648-
},
649-
otherAsyncStuff ({commit}, args) {
650-
return new Promise.resolve(result)
664+
return new Promise.resolve("")
651665
}
652666
}
653667
})

0 commit comments

Comments
 (0)