Last active
December 31, 2015 15:19
-
-
Save tlimpanont/8006336 to your computer and use it in GitHub Desktop.
Utility functions for creating query parameters URL for Deployd.com RESTful API mongodb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function createQueryString(query) { | |
| var parts = []; | |
| for (var k in query) { | |
| if (query.hasOwnProperty(k)) { | |
| parts.push(encodeURIComponent(k) + "=" + encodeURIComponent(query[k])); | |
| } | |
| } | |
| return parts.join('&'); | |
| } | |
| function isComplex(obj) { | |
| if (obj) { | |
| for (var k in obj) { | |
| if (obj.hasOwnProperty(k)) { | |
| if (typeof obj[k] !== 'string') { | |
| return true; | |
| } | |
| } | |
| } | |
| } | |
| return false; | |
| } | |
| function encodeIfComplex(query) { | |
| if (isComplex(query)) { | |
| return encodeURI(JSON.stringify(query)); | |
| } else if (query) { | |
| return createQueryString(query); | |
| } | |
| } | |
| // USAGE | |
| var query = { books: {$elemMatch: {title:'Harry Potter'} } }; | |
| var mongo_url_query = encodeIfComplex(query); | |
| // RESULT: %7B%22books%22:%7B%22$elemMatch%22:%7B%22title%22:%22Harry%20Potter%22%7D%7D%7D |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment