diff --git a/package.json b/package.json index 41ef0d0b976..55527c860fa 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "lodash": "^3.9.3", "moment": "^2.10.3", "mongodb-extended-json": "^1.3.1", + "mongodb-language-model": "^0.2.0", "mongodb-schema": "^3.0.0", "numeral": "^1.5.3", "octicons": "https://github.com/github/octicons/archive/v2.2.0.tar.gz", diff --git a/src/refine-view/index.js b/src/refine-view/index.js index 83fcfc2dfe0..17bb2e8d6bf 100644 --- a/src/refine-view/index.js +++ b/src/refine-view/index.js @@ -1,5 +1,8 @@ var AmpersandView = require('ampersand-view'); var EJSON = require('mongodb-extended-json'); +var _ = require('lodash'); +var debug = require('debug')('scout:refine-view:index'); +var Query = require('mongodb-language-model').Query; module.exports = AmpersandView.extend({ template: require('./index.jade'), @@ -36,11 +39,26 @@ module.exports = AmpersandView.extend({ 'input [data-hook=refine-input]': 'inputChanged', 'submit form': 'submit' }, + _cleanupInput: function (input) { + var output = input; + // accept whitespace-only input as empty query + if (_.trim(output) === '') { + output = '{}'; + } + // replace single quotes with double quotes + output = output.replace(/'/g, '"'); + // wrap field names in double quotes + output = output.replace(/([{,])\s*([^,{\s\'"]+)\s*:/g, ' $1 "$2" : '); + return output; + }, inputChanged: function() { // validate user input on the fly - var queryStr = this.queryByHook('refine-input').value; + var queryStr = this._cleanupInput(this.queryByHook('refine-input').value); try { - EJSON.parse(queryStr); + // is it valid eJSON? + var queryObj = EJSON.parse(queryStr); + // is it a valid parsable Query according to the language? + var languageObj = new Query(queryObj, {parse: true}); } catch (e) { this.valid = false; return; @@ -48,10 +66,9 @@ module.exports = AmpersandView.extend({ this.valid = true; }, buttonClicked: function() { - var queryStr = this.queryByHook('refine-input').value; + var queryStr = this._cleanupInput(this.queryByHook('refine-input').value); var queryObj = EJSON.parse(queryStr); this.model.query = queryObj; - // Modifying the query will reset field-list#schema and because we're using // good ampersand, outgoing views will be removed for us automatically. },