Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the "find where" SailsJS blueprint route?

Use Case

I'd like to create a complex query with more than one criterion using the SailsJS "Find Where" blueprint route. However, I am unable to use the equals comparator and the and condition successfully. I couldn't find adequate documentation on how to implement the Find Where route, so I worked through the source code and came up with the following scenarios.

Question

Using the SailsJS Find Where Blueprint Route, how does one implement:

  • the equality comparison
  • the and condition

Success Scenarios

The following scenarios will return the appropriate response:

http://localhost:1337/api/user?name=fred
http://localhost:1337/api/user?where={"name":{"startsWith":"fred"}}
http://localhost:1337/api/user?where={"name":{"endsWith":"fred"}}
http://localhost:1337/api/user?where={"name":{"contains":"fred"}}
http://localhost:1337/api/user?where={"name":{"like":"fred"}}
http://localhost:1337/api/user?where={"or":[{"name":{"startsWith":"fred"}}]}
http://localhost:1337/api/user?where={"or":[{"name":{"startsWith":"fred"}},{"path":{"endsWith":"fred"}}]}

Failure Scenario

The following scenarios return an empty response:

http://localhost:1337/api/user?where={"name":{"equals":"fred"}}
http://localhost:1337/api/user?where={"name":{"=":"fred"}}
http://localhost:1337/api/user?where={"name":{"equal":"fred"}}
http://localhost:1337/api/user?where={"and":[{"name":{"startsWith":"fred"}}]}
http://localhost:1337/api/user?where={"and":[{"name":{"startsWith":"fred"}},{"path":{"endsWith":"fred"}}]}
like image 440
Pete Avatar asked Aug 13 '14 21:08

Pete


1 Answers

To use "and" queries you use the query string syntax and chain criteria together using the ampersand character. For more advanced queries like OR or complex operators its best to write a controller action. If you decide to stick with blueprints you can use most valid Waterline queries encoded as JSON.

For simple queries you use the query string method. The following would build an "and" query for name and school.

http://localhost:1337/api/user?name=fred&school=foo

To chain together more advanced operators the following should work:

http://localhost:1337/api/user?where={"name":{"startsWith":"fred"},"path":{"endsWith":"fred"}}
like image 87
particlebanana Avatar answered Oct 31 '22 04:10

particlebanana