├── .editorconfig ├── .eslintrc.json ├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── index.js ├── package.json └── test └── index.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = "utf-8" 5 | end_of_line = lf 6 | indent_style = tab 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | 10 | [{package.json}] 11 | indent_size = 2 12 | indent_style = space 13 | 14 | [*.yml] 15 | indent_size = 2 16 | indent_style = space 17 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint:recommended", 3 | "env": { 4 | "node": true, 5 | "es6": true 6 | }, 7 | "parserOptions": { 8 | "sourceType": "module" 9 | }, 10 | "rules": { 11 | "no-console": [ "error" ], 12 | "indent": [ 13 | "error", 14 | "tab", 15 | { 16 | "SwitchCase": 1 17 | } 18 | ], 19 | "linebreak-style": [ 20 | "error", 21 | "unix" 22 | ], 23 | "quotes": [ 24 | "error", 25 | "single", { 26 | "avoidEscape": true 27 | } 28 | ], 29 | "semi": [ 30 | "error", 31 | "never" 32 | ], 33 | "no-console": [ 34 | "off" 35 | ], 36 | "curly": [ 37 | "error" 38 | ], 39 | "eqeqeq": [ 40 | "warn" 41 | ], 42 | "no-unused-vars": [ 43 | "warn" 44 | ], 45 | "no-undef": [ 46 | "error" 47 | ], 48 | "dot-notation": [ 49 | "error" 50 | ], 51 | "eol-last": [ 52 | "error" 53 | ], 54 | "no-multiple-empty-lines": [ 55 | "error", 56 | { 57 | "max": 2, 58 | "maxBOF": 0, 59 | "maxEOF": 1 60 | } 61 | ], 62 | "no-trailing-spaces": [ 63 | "error" 64 | ], 65 | "space-in-parens": [ 66 | "error", 67 | "never" 68 | ], 69 | "space-infix-ops": [ 70 | "error" 71 | ], 72 | "no-redeclare": [ 73 | "error" 74 | ], 75 | "no-useless-concat": [ 76 | "warn" 77 | ], 78 | "prefer-template": [ 79 | "warn" 80 | ], 81 | "no-useless-escape": [ 82 | "error" 83 | ], 84 | "no-shadow-restricted-names": [ 85 | "error" 86 | ], 87 | "no-undef-init": [ 88 | "error" 89 | ], 90 | "no-path-concat": [ 91 | "error" 92 | ], 93 | "no-sync": [ 94 | "warn" 95 | ], 96 | "array-bracket-spacing": [ 97 | "error", 98 | "always" 99 | ], 100 | "object-curly-spacing": [ 101 | "error", 102 | "always" 103 | ], 104 | "computed-property-spacing": [ 105 | "error", 106 | "never" 107 | ], 108 | "block-spacing": [ 109 | "error", 110 | "always" 111 | ], 112 | "space-before-blocks": [ 113 | "error", 114 | "always" 115 | ], 116 | "keyword-spacing": [ 117 | "error", 118 | { 119 | "before": true, 120 | "after": true, 121 | "overrides": { 122 | "catch": { "after": false }, 123 | "for": { "after": false }, 124 | "if": { "after": false }, 125 | "import": { "before": false }, 126 | "switch": { "after": false }, 127 | "while": { "after": false }, 128 | "with": { "after": false } 129 | } 130 | } 131 | ], 132 | "brace-style": [ 133 | "error", 134 | "1tbs", 135 | { 136 | "allowSingleLine": true 137 | } 138 | ], 139 | "comma-spacing": [ 140 | "error", 141 | { 142 | "before": false, 143 | "after": true 144 | } 145 | ], 146 | "spaced-comment": [ 147 | "error", 148 | "always", 149 | { 150 | "exceptions": [ "*" ] 151 | } 152 | ], 153 | "key-spacing": [ 154 | "error", 155 | { 156 | "beforeColon": false, 157 | "afterColon": true, 158 | "mode": "strict" 159 | } 160 | ], 161 | "max-depth": [ 162 | "warn", 163 | { 164 | "max": 4 165 | } 166 | ], 167 | "max-len": [ 168 | "warn", 169 | { 170 | "code": 120, 171 | "ignoreUrls": true 172 | } 173 | ], 174 | "max-lines": [ 175 | "warn" 176 | ], 177 | "no-lonely-if": [ 178 | "warn" 179 | ], 180 | "no-mixed-spaces-and-tabs": [ 181 | "error" 182 | ], 183 | "no-mixed-operators": [ 184 | "error" 185 | ], 186 | "func-call-spacing": [ 187 | "error", 188 | "never" 189 | ], 190 | "no-unneeded-ternary": [ 191 | "warn" 192 | ], 193 | "no-whitespace-before-property": [ 194 | "error" 195 | ], 196 | "no-var": [ 197 | "error" 198 | ], 199 | "one-var": [ 200 | "error", 201 | "never" 202 | ], 203 | "operator-assignment": [ 204 | "warn", 205 | "always" 206 | ], 207 | "quote-props": [ 208 | "error", 209 | "as-needed" 210 | ], 211 | "space-before-function-paren": [ 212 | "error", 213 | "never" 214 | ], 215 | "arrow-spacing": [ 216 | "error", 217 | { 218 | "before": true, 219 | "after": true 220 | } 221 | ], 222 | "constructor-super": [ 223 | "error" 224 | ], 225 | "no-class-assign": [ 226 | "error" 227 | ], 228 | "no-useless-constructor": [ 229 | "error" 230 | ], 231 | "prefer-arrow-callback": [ 232 | "error" 233 | ], 234 | "prefer-const": [ 235 | "error" 236 | ], 237 | "prefer-rest-params": [ 238 | "error" 239 | ], 240 | "prefer-spread": [ 241 | "error" 242 | ] 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/* 3 | npm-debug.log 4 | yarn.lock 5 | test/test.db 6 | coverage 7 | .nyc_output 8 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | npm-debug.log 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6" 4 | - "7" 5 | - "8" 6 | - "node" 7 | sudo: false 8 | script: 9 | - "npm run lint" 10 | - "npm run test-nyc" 11 | cache: 12 | directories: 13 | - node_modules 14 | after_success: 15 | "npm run coverage" 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017-2018 Shmuel Lamm 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # objection-dynamic-finder 2 | 3 | Build Status 4 | Coverage Status 5 | Dependencies 6 | NPM Version 7 | License 8 | 9 | An Objection.js plugin for using convenient finders inspired by Rails's [dynamic finders](http://guides.rubyonrails.org/active_record_querying.html#dynamic-finders). 10 | 11 | ## Examples 12 | 13 | ```js 14 | Person.query().finder.firstNameAndLastName('John', 'Smith') 15 | // => Person.query().where('first_name', 'John').where('last_name', 'Smith') 16 | 17 | Person.query().finder.isDisabledOrStatus(true, 'failed') 18 | // => Person.query().where('is_disabled', true).orWhere('status', 'failed') 19 | 20 | Person.query().finder.firstNameOrFail('Jane') 21 | // If no model is returned, throws an error (uses throwIfNotFound() in Objection > 0.8.1) 22 | 23 | Person.query().finder.firstNameAndNonExistingField('foo') 24 | // => Error 'Querying invalid field: non_existing_field' 25 | // The query fields will be validated against Person model's jsonSchema, if it has one. 26 | 27 | Person.query().avg('income').finder.lastNameAndCountry('Smith', 'USA').where('age', '<', 30) 28 | // Finders can be chained with all other QueryBuilder methods. 29 | ``` 30 | 31 | ## Installation 32 | Due to [Babel not handling](http://babeljs.io/learn-es2015/#ecmascript-2015-features-proxies) the Proxy object, this plugin is only compatible with Node versions >= 6.0.0. 33 | 34 | Add the `objection-dynamic-finder` package via your preferred package manager: 35 | 36 | ```shell 37 | npm install --save objection-dynamic-finder 38 | ``` 39 | 40 | ## Usage 41 | 42 | See Objection.js [docs](http://vincit.github.io/objection.js/#plugin-development-best-practices) on using plugins. Once the plugin is applied to a Model class, that class can use `.finder` in queries. 43 | 44 | ```js 45 | const Finder = require('objection-dynamic-finder') 46 | const Model = require('objection').Model 47 | 48 | class Person extends Finder(Model) { 49 | // ... 50 | } 51 | 52 | ``` 53 | 54 | ## Validation Using jsonSchemas 55 | 56 | _If_ a class has a jsonSchema property defined then the fields in the finder will be validated against the schema to make sure they exist on the model. Make sure the schema is up to date! CamelCase and snake_case property names are both supported. 57 | 58 | ## Contributing 59 | Contributions are always welcome. You are encouraged to open issues and merge requests. 60 | 61 | To run the tests, use `npm run test`. 62 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | module.exports = Model => { 2 | 3 | class FinderQueryBuilder extends Model.QueryBuilder { 4 | 5 | get finder() { 6 | let queryString = null 7 | 8 | // The proxy adds a getter for a query string. 9 | // Upon calling the proxy function, the string is parsed into `where` statements 10 | const proxy = new Proxy((...args) => { 11 | let whereTerm = 'where' 12 | let offsetLetter = '' 13 | let argCount = 0 14 | const schema = this.modelClass().getJsonSchema() 15 | const hasSchema = schema && schema.properties 16 | 17 | // For queryStrings that end in 'OrFail', fail if no models are found ex. firstNameOrFail 18 | if(queryString.slice(-6) === 'OrFail') { 19 | this._failIfNotFound() 20 | queryString = queryString.slice(0, -6) 21 | } 22 | 23 | // Test for beginning 'or' statement ex. orFirstname 24 | if(/^or[A-Z]/.test(queryString)) { 25 | queryString = queryString[2].toLowerCase() + queryString.slice(3) 26 | whereTerm = 'orWhere' 27 | } 28 | 29 | // Split on 'And' or 'Or', using capture groups to keep them in the result set 30 | for(const term of queryString.split(/(?:(Or|And)([A-Z]))/)) { 31 | if(term.length === 1) { 32 | 33 | // Corrects for issue splitting on capture groups 34 | offsetLetter = term 35 | continue 36 | } else if((term === 'And') || (term === 'Or')) { 37 | whereTerm = term === 'And' ? 'where' : 'orWhere' 38 | continue 39 | } 40 | 41 | // Convert query string from camelCase to snake_case 42 | const cameled = (offsetLetter.toLowerCase() + term) 43 | const searchField = cameled.replace(/(.)([A-Z])/, '$1_$2').toLowerCase() 44 | 45 | // If a jsonSchema is defined on the model, use it to validate that the queried fields exist 46 | if(hasSchema) { 47 | if((schema.properties[searchField] === void 0) && (schema.properties[cameled] === void 0)) { 48 | throw new Error( 49 | `Querying invalid field: ${searchField}. Please fix the query or update the jsonSchema.` 50 | ) 51 | } 52 | } 53 | 54 | // Add the where() query 55 | this[whereTerm](searchField, args[argCount ++]) 56 | } 57 | 58 | // Return the QueryBuilder to support further query chaining 59 | return this 60 | }, { 61 | get: (object, prop) => { 62 | queryString = prop 63 | 64 | // Return the proxy so it can then be called 65 | return proxy 66 | } 67 | }) 68 | 69 | // Return the proxy to allow accces to the getter 70 | return proxy 71 | } 72 | 73 | // Use throwIfNotFound on Objection >= 0.8.1. Else mimic its basic functionality. 74 | _failIfNotFound() { 75 | if(typeof this.throwIfNotFound === 'function') { 76 | return this.throwIfNotFound() 77 | } 78 | 79 | return this.runAfter(result => { 80 | if(Array.isArray(result) && result.length === 0) { 81 | throw new Error('No models found') 82 | } else if([ null, undefined, 0 ].includes(result)) { 83 | throw new Error('No models found') 84 | } 85 | 86 | return result 87 | }) 88 | } 89 | 90 | } 91 | 92 | return class extends Model { 93 | static get QueryBuilder() { 94 | return FinderQueryBuilder 95 | } 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "objection-dynamic-finder", 3 | "version": "0.1.4", 4 | "description": "Dynamic finders for Objection.js", 5 | "main": "index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/snlamm/objection-dynamic-finder.git" 9 | }, 10 | "author": "Shmuel Lamm (@snlamm)", 11 | "license": "MIT", 12 | "engines": { 13 | "node": ">=6.0.0" 14 | }, 15 | "devDependencies": { 16 | "ava": "^0.25.0", 17 | "coveralls": "^3.0.0", 18 | "eslint": "^4.17.0", 19 | "knex": "^0.14.2", 20 | "nyc": "^11.4.1", 21 | "objection": "^0.9.4", 22 | "sqlite3": "^3.1.13" 23 | }, 24 | "keywords": [ 25 | "objection", 26 | "objectionjs", 27 | "dynamic-finders", 28 | "dynamic", 29 | "finders", 30 | "orm", 31 | "plugin", 32 | "plugins", 33 | "findby" 34 | ], 35 | "scripts": { 36 | "lint": "eslint index.js", 37 | "test": "ava --verbose", 38 | "test-nyc": "nyc ava --verbose", 39 | "coverage": "nyc report --reporter=text-lcov | coveralls" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | const test = require('ava') 2 | const knex = require('knex') 3 | const Model = require('objection').Model 4 | const Finder = require('../index.js') 5 | 6 | // create knex connection to database 7 | const db = knex({ 8 | client: 'sqlite3', 9 | connection: { filename: './test/test.db' }, 10 | useNullAsDefault: true 11 | }) 12 | 13 | // bind knex instance to objection 14 | Model.knex(db) 15 | 16 | class Person extends Finder(Model) { 17 | static get tableName() { 18 | return 'persons' 19 | } 20 | 21 | static get jsonSchema() { 22 | return { 23 | properties: { 24 | id: { type: 'integer' }, 25 | firstName: { type: 'string' }, 26 | lastName: { type: 'string' }, 27 | email: { type: 'string' } 28 | } 29 | } 30 | } 31 | } 32 | 33 | test('Using a single field', t => { 34 | return Person.query().finder.firstName('John').then(persons => { 35 | t.is(persons[0].first_name, 'John') 36 | }) 37 | }) 38 | 39 | test('Using multiple fields with "and"', t => { 40 | return Person.query().finder.firstNameAndLastName('John', 'Smith').then(persons => { 41 | t.is(persons.length, 1) 42 | t.is(persons[0].last_name, 'Smith') 43 | }) 44 | }) 45 | 46 | test('Using multiple fields with "or"', t => { 47 | return Promise.all([ 48 | Person.query().finder.firstNameAndEmailOrLastName('Jane', 'jane@ccc.com', 'Adams'), 49 | Person.query().finder.firstNameAndEmailOrLastName('Jane', 'john.adam@xyz.com', 'Adams') 50 | ]).then(([ persons, person ]) => { 51 | t.is(persons.length, 2) 52 | 53 | const lastNames = persons.map(person => person.last_name) 54 | t.is(lastNames.includes('Adams'), true) 55 | t.is(lastNames.includes('Quincy'), true) 56 | 57 | t.is(person.length, 1) 58 | t.is(person[0].last_name, 'Adams') 59 | }) 60 | }) 61 | 62 | test('Using a beginning "or"', t => { 63 | const personsQuery = Person.query() 64 | personsQuery.where('email', 'john.adam@xyz.com') 65 | personsQuery.finder.orFirstName('Jane') 66 | 67 | return personsQuery.then(persons => { 68 | t.is(persons.length, 2) 69 | 70 | const lastNames = persons.map(person => person.last_name) 71 | t.is(lastNames.includes('Adams'), true) 72 | t.is(lastNames.includes('Quincy'), true) 73 | }) 74 | }) 75 | 76 | test('Find or fail', t => { 77 | const personsQuery = Person.query().finder.firstNameOrFail('Jim') 78 | 79 | return personsQuery.then(() => t.fail()) 80 | .catch(err => { 81 | t.is(err.message, 'NotFoundError') 82 | }) 83 | }) 84 | 85 | test('Find or fail. Stub Objection version < 0.8.1', t => { 86 | const throwIfNotFound = Person.QueryBuilder.prototype.throwIfNotFound 87 | Person.QueryBuilder.prototype.throwIfNotFound = null 88 | 89 | const personsQuery = Person.query().finder.firstNameOrFail('Jim') 90 | const updatePersonQuery = Person.query().finder.firstNameOrFail('Jim').update({ email: 'jim@abc.com' }) 91 | const successfulPersonsQuery = Person.query().finder.firstNameOrFail('John') 92 | 93 | return successfulPersonsQuery.then(() => { 94 | return personsQuery.then(() => { 95 | Person.QueryBuilder.prototype.throwIfNotFound = throwIfNotFound 96 | t.fail() 97 | }).catch(err => { 98 | t.is(err.message, 'No models found') 99 | }).then(() => { 100 | return updatePersonQuery.then(() => { 101 | Person.QueryBuilder.prototype.throwIfNotFound = throwIfNotFound 102 | t.fail() 103 | }).catch(err => { 104 | Person.QueryBuilder.prototype.throwIfNotFound = throwIfNotFound 105 | t.is(err.message, 'No models found') 106 | }) 107 | }) 108 | }).catch(() => t.fail()) 109 | }) 110 | 111 | test('Querying on a non-existing field fails', t => { 112 | try { 113 | Person.query().finder.asdfead('Jane') 114 | t.fail() 115 | } catch(err) { 116 | t.is(err.message, 'Querying invalid field: asdfead. Please fix the query or update the jsonSchema.') 117 | } 118 | }) 119 | 120 | test('Querying on a non-existing field fails even without a jsonSchema', t => { 121 | const schema = Person.$$jsonSchema 122 | Person.$$jsonSchema = null 123 | 124 | return Person.query().finder.firstName('John').first().then(person => { 125 | t.is(person.first_name, 'John') 126 | 127 | return Person.query().finder.ffffirstName('John').first().then(() => { 128 | Person.$$jsonSchema = schema 129 | t.fail() 130 | }).catch(err => { 131 | t.is(err.message.includes('SQLITE_ERROR: no such column: ffffirst_name'), true) 132 | }) 133 | }) 134 | }) 135 | 136 | test('Continue chaining queries on top of finder', t => { 137 | return Person.query().finder.firstName('John').where('last_name', 'Adams').first().then(person => { 138 | t.is(person.last_name, 'Adams') 139 | }) 140 | }) 141 | 142 | test.before(() => { 143 | return db.schema.createTableIfNotExists('persons', table => { 144 | table.increments('id').primary() 145 | table.string('first_name') 146 | table.string('last_name') 147 | table.string('email') 148 | }).then(() => { 149 | return db('persons').delete() 150 | }).then(() => { 151 | return Promise.all([ 152 | Person.query().insert({ first_name: 'John', last_name: 'Smith', email: 'john.smith@xyz.com' }), 153 | Person.query().insert({ first_name: 'John', last_name: 'Adams', email: 'john.adam@xyz.com' }), 154 | Person.query().insert({ first_name: 'Jane', last_name: 'Quincy', email: 'jane@ccc.com' }) 155 | ]) 156 | }) 157 | }) 158 | 159 | test.after(() => { 160 | return db.schema.dropTable('persons').then(() => db.destroy()) 161 | }) 162 | --------------------------------------------------------------------------------