Add _like operator, credit goes to @tony-kerz for the idea

This commit is contained in:
Typicode
2015-12-13 15:43:05 +01:00
parent 3f933b06e6
commit a38d748fe0
5 changed files with 35 additions and 6 deletions

View File

@ -1,5 +1,11 @@
# Change Log
## [0.8.4][2015-12-13]
### Added
* Like operator `GET /posts?title_like=json` (accepts RegExp)
## [0.8.3][2015-11-25]
### Added

View File

@ -112,6 +112,12 @@ Add `_ne` to exclude a value
GET /posts?id_ne=1
```
Add `_like` to filter using RegExp
```
GET /posts?title_like=server
```
### Full-text search
Add `q`

View File

@ -35,7 +35,9 @@
"supertest": "~0.8.1"
},
"scripts": {
"test": "NODE_ENV=test mocha -R spec test/**/*.js && standard",
"test": "npm run test:cli && npm run test:server && standard",
"test:cli": "NODE_ENV=test mocha -R spec test/cli/*.js",
"test:server": "NODE_ENV=test mocha -R spec test/server/*.js",
"start": "node bin",
"prepush": "npm t"
},

View File

@ -74,7 +74,8 @@ module.exports = function (db, name) {
query === '_' ||
query.indexOf('_lte') !== -1 ||
query.indexOf('_gte') !== -1 ||
query.indexOf('_ne') !== -1
query.indexOf('_ne') !== -1 ||
query.indexOf('_like') !== -1
) return
}
delete req.query[query]
@ -109,12 +110,12 @@ module.exports = function (db, name) {
.map(function (value) {
var isDifferent = key.indexOf('_ne') !== -1
var isRange = key.indexOf('_lte') !== -1 || key.indexOf('_gte') !== -1
var path = key.replace(/(_lte|_gte|_ne)$/, '')
var elementValue
var isLike = key.indexOf('_like') !== -1
var path = key.replace(/(_lte|_gte|_ne|_like)$/, '')
var elementValue = _.get(element, path)
if (isRange) {
var isLowerThan = key.indexOf('_gte') !== -1
elementValue = _.get(element, path)
if (isLowerThan) {
return value <= elementValue
@ -122,8 +123,9 @@ module.exports = function (db, name) {
return value >= elementValue
}
} else if (isDifferent) {
elementValue = _.get(element, path)
return value !== elementValue
} else if (isLike) {
return new RegExp(value).test(elementValue)
} else {
return _.matchesProperty(key, value)(element)
}

View File

@ -244,6 +244,19 @@ describe('Server', function () {
})
})
describe('GET /:resource?attr_like=', function () {
it('should respond with an array that matches the like operator', function (done) {
request(server)
.get('/tags?body_like=hoto')
.expect('Content-Type', /json/)
.expect([
db.tags[1],
db.tags[2]
])
.expect(200, done)
})
})
describe('GET /:parent/:parentId/:resource', function () {
it('should respond with json and corresponding nested resources', function (done) {
request(server)