Skip to content

Commit

Permalink
Add jsonpath for getter filtering.
Browse files Browse the repository at this point in the history
  • Loading branch information
mrichar1 committed Oct 15, 2018
1 parent bea2386 commit a91db1c
Show file tree
Hide file tree
Showing 4 changed files with 194 additions and 54 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
},
"dependencies": {
"deepmerge": "^2.2.1",
"jsonpath": "^1.0.0",
"mocha-eslint": "^4.1.0",
"vue": "^2.5.17"
}
Expand Down
5 changes: 5 additions & 0 deletions spec/jsonapi-vuex.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,11 @@ describe("jsonapi-vuex tests", () => {
const result = get(store_item1)('widget/1')
expect(result).to.deep.equal(norm_item1)
})
it("should filter results using jsonpath", () => {
const { get } = jm.getters
const result = get(store_record)('widget', '$[?(@.bar=="baz")]')
expect(result).to.deep.equal(norm_item1)
})
it("should return empty object if type not in state", () => {
const { get } = jm.getters
const result = get({})('widget')
Expand Down
15 changes: 14 additions & 1 deletion src/jsonapi-vuex.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import Vue from 'vue'
import merge from 'deepmerge';
// https://github.com/dchester/jsonpath/issues/89
import jp from 'jsonpath/jsonpath.min'


const mutations = (api) => { // eslint-disable-line no-unused-vars
return {
Expand Down Expand Up @@ -116,7 +119,7 @@ const actions = (api) => {

const getters = (api) => { // eslint-disable-line no-unused-vars
return {
get: (state) => (data) => {
get: (state) => (data, jsonpath) => {
if (!data) {
// No data arg - return whole state object
return state
Expand All @@ -142,6 +145,16 @@ const getters = (api) => { // eslint-disable-line no-unused-vars
return {}
}

// Filter by jsonpath
if (jsonpath) {
const filtered = jp.query(result, jsonpath)
if (Array.isArray(filtered)) {
result = {}
for (let item of filtered) {
result[item['_jv']['id']] = item
}
}
}
// Prune index id if only 1 item
const keys = Object.keys(result)
if (keys.length === 1) {
Expand Down
Loading

0 comments on commit a91db1c

Please sign in to comment.