1

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?

alexandru.topliceanu
  • 2,364
  • 2
  • 27
  • 38
  • This might work: https://github.com/wearefractal/node-linq – Blender Apr 24 '13 at 03:05
  • Thanks @Bender. I realize now that this question has already been asked http://stackoverflow.com/questions/15397668/what-javascript-library-can-evaluate-mongodb-like-query-predicates-against-an-ob?rq=1 and linq was proposed there as well. It's not really what I'm looking for. – alexandru.topliceanu Apr 24 '13 at 03:13
  • Ok, so I've found something that does prettymuch what I want to do [crcn/sift.js](https://github.com/crcn/sift.js) by Craig Condon. – alexandru.topliceanu Apr 24 '13 at 03:36
  • The title of this question is a little bit misleading, sounds like you want a library to do `querySelector` kinds of things. You might want to rewrite it along the lines of "Is there a JavaScript object query language?" or something. –  Oct 12 '14 at 12:10

1 Answers1

0

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.

alexandru.topliceanu
  • 2,364
  • 2
  • 27
  • 38