Skip to content

Commit 165b144

Browse files
committed
Add global search
1 parent 96f2112 commit 165b144

File tree

2 files changed

+52
-4
lines changed

2 files changed

+52
-4
lines changed

src/routes.js

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,26 @@ routes.list = function(req, res, next) {
2626
}
2727

2828
for (var key in req.query) {
29-
if (key !== 'callback') props[key] = utils.toNative(req.query[key])
29+
if (key !== 'callback' && key != 'q') props[key] = utils.toNative(req.query[key])
3030
}
3131

32-
if (_(props).isEmpty()) {
32+
if(req.query.q !== undefined) {
33+
var q = req.query.q.toLowerCase(),
34+
keys = _.keys(low(req.params.resource).first()),
35+
callback = function(element) {
36+
for(var i in keys) {
37+
var value = element[keys[i]];
38+
39+
if (value === q || (_.isString(value) && value.toLowerCase().indexOf(q) !== -1)) {
40+
return true;
41+
}
42+
}
43+
44+
return false;
45+
}
46+
47+
resource = low(req.params.resource).where(callback).value()
48+
} else if (_(props).isEmpty()) {
3349
resource = low(req.params.resource).value()
3450
} else {
3551
resource = low(req.params.resource).where(props).value()
@@ -92,4 +108,4 @@ routes.destroy = function(req, res, next) {
92108
res.send(204)
93109
}
94110

95-
module.exports = routes
111+
module.exports = routes

test/server.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ describe('Server', function() {
1313
{id: 2, body: 'bar'}
1414
]
1515

16+
low.db.tags = [
17+
{id: 1, body: 'Technology'},
18+
{id: 2, body: 'Photography'},
19+
{id: 3, body: 'photo'}
20+
]
21+
1622
low.db.comments = [
1723
{id: 1, published: true, postId: 1},
1824
{id: 2, published: false, postId: 1},
@@ -55,6 +61,32 @@ describe('Server', function() {
5561
})
5662
})
5763

64+
describe('GET /:resource?q=value', function() {
65+
it('should respond with json and filter all begin of fields of resources', function(done) {
66+
request(server)
67+
.get('/tags?q=photo')
68+
.expect('Content-Type', /json/)
69+
.expect([low.db.tags[1], low.db.tags[2]])
70+
.expect(200, done)
71+
})
72+
73+
it('should respond with json and filter everywhere of all fields of resources', function(done) {
74+
request(server)
75+
.get('/tags?q=t')
76+
.expect('Content-Type', /json/)
77+
.expect(low.db.tags)
78+
.expect(200, done)
79+
})
80+
81+
it('should not respond anything when the query does not many any data', function(done) {
82+
request(server)
83+
.get('/tags?q=nope')
84+
.expect('Content-Type', /json/)
85+
.expect([])
86+
.expect(200, done)
87+
})
88+
})
89+
5890
describe('GET /:resource?_start=&_end=', function() {
5991
it('should respond with sliced array', function(done) {
6092
request(server)
@@ -171,4 +203,4 @@ describe('Server', function() {
171203
});
172204

173205
})
174-
})
206+
})

0 commit comments

Comments
 (0)