Javascript Query Selectors DSL as an Independent Library

I really like mongodb's json dsl for querying the database. I was wondering if there is any stand alone library for node.js/browser that can convert that kind of json expressions into, maybe, js functions that you can apply on certain context object.

Here's what I mean. Say you have the following expression:

{
  "context.user.age": { "$gte": 30, "$lte": 40 },
  "context.user.hobby": { "$in": ["swimming", "running"] }
}

This could be translated into a js function:

var f = function (context) {
  // @return {Boolean}
  return (context.user.age >= 30) &&
         (context.user.age <= 40) &&
         (['swimming', 'running'].indexOf(context.user.hobby) >= 0)
}

I need this because I'm building my own DSL. So, do you know anything with this kind of functionality?

There are at least two libs that perform similar or easily adaptable functionality as that described in the question body.

  • Benjamin Arthur Lupton's query-engine, feature rich
  • Craig Condon's sift, lightweight

To produce my boolean returning function I wrote this (using sift):

   parseCondition = (condition) ->
        ###
            @param {Object} condition - a condition statement written in swift.
            @return {Function} - condition fn to be applied on a context
                                 which will return a Boolean.
            @see https://github.com/crcn/sift.js
        ###
        return (context) ->
            [expectedContext] = swift condition, [context]
            return expectedContext is context

I'm passing in the context object and checking if the returned object is the same. If it is, then the condition was passed.

Have a look at just few lines implementation in https://github.com/mirek/node-json-criteria.