├── .nvmrc ├── .eslintrc.js ├── .gitignore ├── index.js ├── Jenkinsfile ├── LICENSE ├── package.json ├── lib └── sieve.js ├── README.md └── test └── sieve.test.js /.nvmrc: -------------------------------------------------------------------------------- 1 | 16 -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "extends": "standard" 3 | }; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | bower_components 3 | package-lock.json -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const Sieve = require('./lib/sieve') 2 | 3 | module.exports = Sieve 4 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent { 3 | docker { 4 | image 'node:16' 5 | args '-v /home/ec2-user/.npmrc:/home/node/.npmrc:ro' 6 | } 7 | } 8 | 9 | stages { 10 | stage('Build') { 11 | steps { 12 | sh ''' 13 | npm ci 14 | ''' 15 | } 16 | } 17 | 18 | stage('Publish') { 19 | when { 20 | branch 'master' 21 | } 22 | steps { 23 | sh ''' 24 | BASEVERSION=`node -e "var pjson = require('./package.json'); console.log(pjson.version);" | cut -d"." -f1,2` 25 | npm version "$BASEVERSION.$BUILD_NUMBER" 26 | npm publish 27 | ''' 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Maurizio Lupo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "obj-sieve", 3 | "version": "1.0.0", 4 | "description": "Skim an object of unnecessary data", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "mocha", 8 | "watch": "npm run test -- -w", 9 | "lint": "eslint --fix --ext .js ./lib ./test", 10 | "precommit": "npm run lint", 11 | "prepush": "npm run test" 12 | }, 13 | "publishConfig": { 14 | "registry": "https://npm.tescloud.com" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/tes/obj-sieve.git" 19 | }, 20 | "keyword": [], 21 | "author": "Maurizio Lupo ", 22 | "license": "MIT", 23 | "dependencies": { 24 | "iter-tools": "^1.4.1", 25 | "lodash": "^4.17.11", 26 | "obj-delta": "0.0.3", 27 | "obj-path-expression-parser": "github:tes/obj-path-expression-parser" 28 | }, 29 | "devDependencies": { 30 | "chai": "^4.1.2", 31 | "eslint": "^8.1.0", 32 | "eslint-config-standard": "^10.2.1", 33 | "eslint-plugin-import": "^2.8.0", 34 | "eslint-plugin-node": "^5.2.1", 35 | "eslint-plugin-promise": "^3.6.0", 36 | "eslint-plugin-standard": "^3.0.1", 37 | "husky": "^0.14.3", 38 | "mocha": "^9.1.3" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lib/sieve.js: -------------------------------------------------------------------------------- 1 | const _get = require('lodash/get') 2 | const _isUndefined = require('lodash/isUndefined') 3 | const _isPlainObject = require('lodash/isPlainObject') 4 | const Delta = require('obj-delta') 5 | 6 | const expressionParser = require('obj-path-expression-parser') 7 | 8 | function Sieve (paths) { 9 | if (!(this instanceof Sieve)) { 10 | return new Sieve(paths) 11 | } 12 | this._paths = paths || {} 13 | this._paths.include = this._paths.include || [] 14 | this._paths.exclude = this._paths.exclude || [] 15 | this._customFunctions = {} 16 | } 17 | 18 | Sieve.prototype.setCustomFunctions = function setCustomFunctions (customFunctions) { 19 | this._customFunctions = customFunctions || {} 20 | } 21 | 22 | Sieve.prototype.include = function include (path) { 23 | this._paths.include.push(path) 24 | return this 25 | } 26 | 27 | Sieve.prototype.exclude = function include (path) { 28 | this._paths.exclude.push(path) 29 | return this 30 | } 31 | 32 | Sieve.prototype.toJSON = function () { 33 | return this._paths 34 | } 35 | 36 | Sieve.prototype.apply = function (obj) { 37 | if (!this._paths.include.length && !this._paths.exclude.length) { 38 | return obj 39 | } 40 | const delta = new Delta() 41 | const includePaths = this._paths.include.length ? this._paths.include : ['*'] 42 | for (const pathEpression of includePaths) { 43 | for (const path of expressionParser(pathEpression, obj, this._customFunctions)) { 44 | const value = _get(obj, path) 45 | if (!_isUndefined(value)) { 46 | delta.set(path, value) 47 | } 48 | } 49 | } 50 | 51 | for (const pathEpression of this._paths.exclude) { 52 | for (const path of expressionParser(pathEpression, obj, this._customFunctions)) { 53 | delta.del(path) 54 | } 55 | } 56 | const output = delta.apply(Array.isArray(obj) ? [] : {}) 57 | return output 58 | } 59 | 60 | Sieve.filter = function filter (paths, obj, customFunctions) { 61 | let include 62 | let exclude 63 | if (_isPlainObject(paths)) { 64 | include = paths.include 65 | exclude = paths.exclude 66 | } else { 67 | include = paths 68 | } 69 | const sieve = new Sieve() 70 | sieve.setCustomFunctions(customFunctions) 71 | include && sieve.include(include) 72 | exclude && sieve.exclude(exclude) 73 | return sieve.apply(obj) 74 | } 75 | 76 | module.exports = Sieve 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | obj-sieve 2 | ========= 3 | Skim an object of unnecessary data. 4 | 5 | Why 6 | --- 7 | Every time you have a big json to save to a db or to send through the wire you should remove all unneccesary data. This library reduce all the work to a function call with an easy to understand expression. 8 | 9 | Importing and creating a sieve instance 10 | --------------------------------------- 11 | ```js 12 | const Sieve = require('obj-sieve'); 13 | const sieve = new Sieve(); 14 | ``` 15 | 16 | Example 17 | ------- 18 | This is our original object: 19 | ```js 20 | const characters = { 21 | heroes: [ 22 | { 23 | title: 'mr', 24 | name: 'Bruce Wayne', 25 | secretIdentity: 'batman', 26 | base: 'batcave', 27 | }, 28 | { 29 | title: 'mr', 30 | name: 'Clarke Kent', 31 | secretIdentity: 'superman', 32 | base: 'fortress of solitude', 33 | }, 34 | { 35 | title: 'princess', 36 | name: 'Diana Prince', 37 | secretIdentity: 'wonder woman', 38 | base: 'Themyscira', 39 | } 40 | ], 41 | villains: [ 42 | { 43 | title: 'mr', 44 | name: 'Jack Napier', 45 | secretIdentity: 'the joker', 46 | base: 'Unknown', 47 | } 48 | ] 49 | }; 50 | ``` 51 | Let's say you are only interested in heroes, and only their cover identities (you don't want to save secret informations on our db after all!). 52 | You can use this expression: 53 | ```js 54 | sieve.include('heroes[:][name|title]'); 55 | ``` 56 | That means every item in "heroes" array, but only the fields "name" and "title" (I explain the path expressions below). You can use the method include multiple times, to add different part of the object you are interested in keeping. 57 | ```js 58 | const filteredCharacters = sieve.apply(characters); 59 | ``` 60 | filteredCharacter contains: 61 | ```js 62 | const filteredCharacters = { 63 | heroes: [ 64 | { 65 | title: 'mr', 66 | name: 'Bruce Wayne', 67 | }, 68 | { 69 | title: 'mr', 70 | name: 'Clarke Kent', 71 | }, 72 | { 73 | title: 'princess', 74 | name: 'Diana Prince', 75 | } 76 | ], 77 | }; 78 | ``` 79 | 80 | Path expressions 81 | ================ 82 | You can find a full explanation of path expressions here: https://github.com/sithmel/obj-path-expression-parser 83 | 84 | A path expression is composed by comma separated paths. Like: 85 | ``` 86 | hello.world,x.y 87 | ``` 88 | Every path contains a certain number of fragments. "hello", "world", "x" and "y" are fragments. 89 | Fragments tries to match a value in an object. For example, the expression will find 2 matches in this object: 90 | ``` 91 | { 92 | hello: { 93 | world: 'here' 94 | }, 95 | x: { 96 | y: 'and here' 97 | } 98 | } 99 | ``` 100 | A fragment can use the globbing syntax to match multiple properties. 101 | ``` 102 | hello[*] 103 | ``` 104 | will match: 105 | ``` 106 | { 107 | hello: { 108 | world: 'here' 109 | mars: 'and here' 110 | }, 111 | x: { 112 | y: 'not here' 113 | } 114 | } 115 | ``` 116 | You can notice that you can use a dot or square brackets to separate the fragments. Between square brackets you can use any character (but you'll have to escape other square brackets with a backslash). You can also use escaping to match characters used in globbing (* and ? for example). 117 | Here's what you can do with globbing: 118 | * xyz: it matches only the attribute "xyz" 119 | * xyz|abc: it matches both "xyz" and "abc" 120 | * `*` : it matches all attributes 121 | * !abc: it matches everything except abc 122 | * test?: it matches "test1", "test2", "test3". It doesn't match "test" or "test10" 123 | * test*: it matches "test1", "test2", "test3", "test" and "test10" 124 | 125 | When matching an array you can use the slice notation. It uses ":" to separate 2 indexes (it uses the same syntax as Array.prototype.slice, or Python slices). 126 | The first number is where the slice starts. If omitted it will be considered 0. 127 | The second number is where the slice ends. If omitted it will be considered equal to the length of the array. 128 | Negative numbers are calculated from the end of the array. 129 | For Example: 130 | * [:] of [1, 2, 3, 4] = [1, 2, 3, 4] **all** 131 | * [1:] of [1, 2, 3, 4] = [2, 3, 4] **all excepti the first** 132 | * [:1] of [1, 2, 3, 4] = [1] **to the one with index 1** 133 | * [:-1] of [1, 2, 3, 4] = [1, 2, 3] **to the one before the last** 134 | * [1:-1] of [1, 2, 3, 4] = [2, 3] **from the one with index one to the one before the last** 135 | * [-2:] of [1, 2, 3, 4] = [3, 4] **the last 2** 136 | 137 | Nested path expressions 138 | ----------------------- 139 | A fragment can contain a nested path expression (using round parenthesis): 140 | ``` 141 | users(x,y,z)name 142 | ``` 143 | This will match: 144 | ``` 145 | { 146 | users: { 147 | x: { name: 'mr X' }, 148 | y: { name: 'mr Y' }, 149 | z: { name: 'mr Z' }, 150 | } 151 | } 152 | ``` 153 | 154 | Custom functions 155 | ---------------- 156 | A custom function can be used to enable a more complex filtering. You can add a custom function with: 157 | ```js 158 | sieve.setCustomFunctions({ 159 | '=': (path, funcArgument, parent) => { 160 | const [fieldName, value] = funcArgument.split(',') 161 | if (_isPlainObject(parent) && _get(parent, fieldName).toString() === value) { 162 | return [path] 163 | } 164 | return [] 165 | } 166 | }) 167 | ``` 168 | Then you can use the custom function like this: 169 | ```js 170 | sieve.include('heroes[:]{= title,mr}[name]') 171 | ``` 172 | You put the custom function between curly braces. The name of the function is the first string ("=" in this case), the argument is the rest of the fragment (title,mr). 173 | A custom function takes the current path, the argument, and the current object. 174 | It should returns an arrays of paths. In the example I am either passing an empty array or an array with a single path. I am filtering what path include and what don't. 175 | 176 | exclude 177 | ------- 178 | In case you need to filter out some of the content you are including, there is a method exclude. 179 | This method takes a path expression (just like the include method) and uses this to identify what part of the final object we need to remove. 180 | ```js 181 | sieve.include('heroes'); 182 | sieve.exclude('heroes[:][secretIdentity|base]'); 183 | sieve.apply(characters); 184 | ``` 185 | This is importing the heroes array, and then removing "secretIdentity" and "base". 186 | 187 | Additional features 188 | ------------------- 189 | The sieve object is JSON serializable: 190 | ```js 191 | const json = JSON.stringify(sieve); 192 | ``` 193 | You can deserialize it like this: 194 | ```js 195 | const sieve = new Sieve(JSON.parse(json)); 196 | ``` 197 | A shorthand is also available: 198 | ```js 199 | Sieve.filter('hello,world', { hello: 1, world: 2, other: 3}); 200 | // returns: { hello: 1, world: 2 } 201 | ``` 202 | that is equivalent to: 203 | ```js 204 | const sieve = new Sieve(); 205 | sieve.include('hello'); 206 | sieve.include('world'); 207 | sieve.apply({ hello: 1, world: 2, other: 3}); 208 | // returns: { hello: 1, world: 2 } 209 | ``` 210 | 211 | ES compatibility 212 | ---------------- 213 | This package is compatible with ES2015 (ES6) as it uses ES generators. 214 | -------------------------------------------------------------------------------- /test/sieve.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-env node, mocha */ 2 | const assert = require('chai').assert 3 | const Sieve = require('..') 4 | const _isPlainObject = require('lodash/isPlainObject') 5 | const _get = require('lodash/get') 6 | 7 | describe('sieve', function () { 8 | it('is an object', function () { 9 | assert.typeOf(new Sieve(), 'object') 10 | }) 11 | 12 | it('adds a path', function () { 13 | const sieve = new Sieve() 14 | sieve.include('hello') 15 | assert.deepEqual(sieve._paths.include, ['hello']) 16 | }) 17 | 18 | it('can be serialised', function () { 19 | const sieve = new Sieve() 20 | sieve.include('hello') 21 | sieve.include('world') 22 | assert.equal(JSON.stringify(sieve), '{"include":["hello","world"],"exclude":[]}') 23 | }) 24 | 25 | it('can be deserialised', function () { 26 | const sieve = new Sieve({ include: ['hello.world'] }) 27 | assert.deepEqual(sieve._paths.include, ['hello.world']) 28 | }) 29 | 30 | it('filters an object', function () { 31 | const sieve = new Sieve() 32 | sieve.include('hello') 33 | const newObj = sieve.apply({ 34 | hello: 1, 35 | world: 2 36 | }) 37 | assert.deepEqual(newObj, { hello: 1 }) 38 | }) 39 | 40 | it('filters an object, using shorthand', function () { 41 | const newObj = Sieve.filter('hello', { 42 | hello: 1, 43 | world: 2 44 | }) 45 | assert.deepEqual(newObj, { hello: 1 }) 46 | }) 47 | 48 | it('filters an object with a complex expression', function () { 49 | const sieve = new Sieve() 50 | sieve.include('users[-2:][*Name]') 51 | const newObj = sieve.apply({ 52 | users: [ 53 | { title: 'mr', FirstName: 'Bruce', lastName: 'Wayne' }, 54 | { title: 'mr', FirstName: 'Clarke', lastName: 'Kent' }, 55 | { title: 'ms', FirstName: 'Diana', lastName: 'Prince' }, 56 | { title: 'mr', FirstName: 'Barry', lastName: 'Allen' }, 57 | { title: 'mr', FirstName: 'Arthur', lastName: 'Curry' } 58 | ] 59 | }) 60 | assert.deepEqual(newObj, { 61 | users: [ 62 | { FirstName: 'Barry', lastName: 'Allen' }, 63 | { FirstName: 'Arthur', lastName: 'Curry' } 64 | ] 65 | }) 66 | }) 67 | 68 | it('filters an object with a complex expression (2)', function () { 69 | const sieve = new Sieve() 70 | sieve.include('heroes[:][name|title]') 71 | const newObj = sieve.apply({ 72 | heroes: [ 73 | { 74 | title: 'mr', 75 | name: 'Bruce Wayne', 76 | secretIdentity: 'batman', 77 | base: 'batcave' 78 | }, 79 | { 80 | title: 'mr', 81 | name: 'Clarke Kent', 82 | secretIdentity: 'superman', 83 | base: 'fortress of solitude' 84 | }, 85 | { 86 | title: 'princess', 87 | name: 'Diana Prince', 88 | secretIdentity: 'wonder woman', 89 | base: 'Themyscira' 90 | } 91 | ], 92 | villains: [ 93 | { 94 | title: 'mr', 95 | name: 'Jack Napier', 96 | secretIdentity: 'the joker', 97 | base: 'Unknown' 98 | } 99 | ] 100 | }) 101 | assert.deepEqual(newObj, { 102 | heroes: [ 103 | { 104 | title: 'mr', 105 | name: 'Bruce Wayne' 106 | }, 107 | { 108 | title: 'mr', 109 | name: 'Clarke Kent' 110 | }, 111 | { 112 | title: 'princess', 113 | name: 'Diana Prince' 114 | } 115 | ] 116 | }) 117 | }) 118 | 119 | it('filters an object with a complex expression, using exclude', function () { 120 | const sieve = new Sieve() 121 | sieve.include('heroes[:][name|title]') 122 | sieve.exclude('heroes[:][title]') 123 | const newObj = sieve.apply({ 124 | heroes: [ 125 | { 126 | title: 'mr', 127 | name: 'Bruce Wayne', 128 | secretIdentity: 'batman', 129 | base: 'batcave' 130 | }, 131 | { 132 | title: 'mr', 133 | name: 'Clarke Kent', 134 | secretIdentity: 'superman', 135 | base: 'fortress of solitude' 136 | }, 137 | { 138 | title: 'princess', 139 | name: 'Diana Prince', 140 | secretIdentity: 'wonder woman', 141 | base: 'Themyscira' 142 | } 143 | ], 144 | villains: [ 145 | { 146 | title: 'mr', 147 | name: 'Jack Napier', 148 | secretIdentity: 'the joker', 149 | base: 'Unknown' 150 | } 151 | ] 152 | }) 153 | assert.deepEqual(newObj, { 154 | heroes: [ 155 | { 156 | name: 'Bruce Wayne' 157 | }, 158 | { 159 | name: 'Clarke Kent' 160 | }, 161 | { 162 | name: 'Diana Prince' 163 | } 164 | ] 165 | }) 166 | }) 167 | 168 | it('includes everything when there is no include', function () { 169 | const sieve = new Sieve() 170 | sieve.exclude('heroes[0:2],villains') 171 | const newObj = sieve.apply({ 172 | heroes: [ 173 | { 174 | title: 'mr', 175 | name: 'Bruce Wayne', 176 | secretIdentity: 'batman', 177 | base: 'batcave' 178 | }, 179 | { 180 | title: 'mr', 181 | name: 'Clarke Kent', 182 | secretIdentity: 'superman', 183 | base: 'fortress of solitude' 184 | }, 185 | { 186 | title: 'princess', 187 | name: 'Diana Prince', 188 | secretIdentity: 'wonder woman', 189 | base: 'Themyscira' 190 | } 191 | ], 192 | villains: [ 193 | { 194 | title: 'mr', 195 | name: 'Jack Napier', 196 | secretIdentity: 'the joker', 197 | base: 'Unknown' 198 | } 199 | ] 200 | }) 201 | assert.deepEqual(newObj, { 202 | heroes: [ 203 | { 204 | title: 'princess', 205 | name: 'Diana Prince', 206 | secretIdentity: 'wonder woman', 207 | base: 'Themyscira' 208 | } 209 | ] 210 | }) 211 | }) 212 | 213 | it('filters an object with a complex expression, using exclude, using filter expression', function () { 214 | const sieve = new Sieve() 215 | sieve.setCustomFunctions({ 216 | '=': (path, funcArgument, parent) => { 217 | const [fieldName, value] = funcArgument.split(',') 218 | if (_isPlainObject(parent) && _get(parent, fieldName).toString() === value) { 219 | return [path] 220 | } 221 | return [] 222 | } 223 | }) 224 | sieve.include('heroes[:]{= title,mr}[name]') 225 | const newObj = sieve.apply({ 226 | heroes: [ 227 | { 228 | title: 'mr', 229 | name: 'Bruce Wayne', 230 | secretIdentity: 'batman', 231 | base: 'batcave' 232 | }, 233 | { 234 | title: 'mr', 235 | name: 'Clarke Kent', 236 | secretIdentity: 'superman', 237 | base: 'fortress of solitude' 238 | }, 239 | { 240 | title: 'princess', 241 | name: 'Diana Prince', 242 | secretIdentity: 'wonder woman', 243 | base: 'Themyscira' 244 | } 245 | ], 246 | villains: [ 247 | { 248 | title: 'mr', 249 | name: 'Jack Napier', 250 | secretIdentity: 'the joker', 251 | base: 'Unknown' 252 | } 253 | ] 254 | }) 255 | assert.deepEqual(newObj, { 256 | heroes: [ 257 | { 258 | name: 'Bruce Wayne' 259 | }, 260 | { 261 | name: 'Clarke Kent' 262 | } 263 | ] 264 | }) 265 | }) 266 | }) 267 | --------------------------------------------------------------------------------